Home > OS >  Edit html with css but now classes
Edit html with css but now classes

Time:06-07

I'm getting ready for a test and one of the main topics will be changing an HTML style using CSS but we can't use HTML classes or edit the HTML.

In order to change the background I used Article and it selected everything inside and the background was changed, I managed to change the color of Hidden and Green by selecting it using only-child, but then I tried with the other ones and couldn't manage to do it.

It should look like this: https://clickio.gyazo.com/97fa4884c612a1653b4b3245d102eb52

article {
  background-color: gray;
}

p:only-child {
  color: green;
}
<article>
  <p>Green</p>
  <p>Blue</p>
  <div>
    <p>Red centered</p>
  </div>
  <p>Yellow</p>
  <p>Green</p>
  <div >
    <p>Hidden</p>
  </div>
  <p>Green</p>
  <p>Green</p>
  <p>Purple</p>
  <p>Pink</p>
  <hr>
</article>

CodePudding user response:

You can utilize nth-child() for your task:

article {
  background-color: gray;
}

article > :nth-child(1),
article > :nth-child(5),
article > :nth-child(7),
article > :nth-child(8) {
  color: green;
}

article > :nth-child(2) {
  color: blue;
}

article > :nth-child(4) {
  color: yellow;
}

article > :nth-child(9) {
  color: purple;
}

article > :nth-child(10) {
  color: pink;
}

article > :nth-child(3) {
  text-align: center;
  color: red;
}

.hidden {
  display: none;
}
<article>
  <p>Green</p>
  <p>Blue</p>
  <div>
    <p>Red centered</p>
  </div>
  <p>Yellow</p>
  <p>Green</p>
  <div >
    <p>Hidden</p>
  </div>
  <p>Green</p>
  <p>Green</p>
  <p>Purple</p>
  <p>Pink</p>
  <hr>
</article>

CodePudding user response:

This is pretty close to the expectations..

It's a matter of crafting css selectors to address the correct elements to style. The demo I'm showing here uses a different css rule for each element. There are surely several ways to style the document as expected and this isn't surely the most compact one. By the way I used mostly the following pseudo-slectors:

  • :nth-child()
  • :nth-of-type()

article {
  background-color: gray;
  padding-left: 1rem;
}

article > p:first-child{
  color: green;
}

article > p:nth-child(2){
  color: blue;  
}

article > div:nth-of-type(1){
  text-align: center;  
  color: red;
  background: white;
  width: 10rem;
  height: 3rem;
}

article > p:nth-child(4){
  color: yellow;
}

article > p:nth-child(5) {
  color: green;
}

article > div.hidden {
  display: none;
}

article > p:nth-child(7) {
  color: green;
}

article > p:nth-child(8) {
  color: green;
}

article > p:nth-child(9) {
  color: purple;
}

article > p:nth-child(10) {
  color: pink;
}
<article>
  <p>Green</p>
  <p>Blue</p>
  <div>
    <p>Red centered</p>
  </div>
  <p>Yellow</p>
  <p>Green</p>
  <div >
    <p>Hidden</p>
  </div>
  <p>Green</p>
  <p>Green</p>
  <p>Purple</p>
  <p>Pink</p>
  <hr>
</article>

  • Related