Home > Blockchain >  How to define a specific style for each page section?
How to define a specific style for each page section?

Time:06-08

Here, each section of a page should have its specific style. For example, in the code below, I'd like that the headers and paragraphs of section-a and section-b had, each, their own style. But it's not working with my approach.

There's no global styles for <p> and <h2> that could be conflicting with those from section-a and section-b.

And I'd prefer not adding the style per line - like <p id="section-a"> - to keep the code cleaner.

h2 {
  font-family: 'Wellfleet', cursive;
}

p {
  font-family: 'Roboto Mono', monospace;
}

h2#section-a {
  color: red;
}

p#section-a {
  color: black;
}

h2#section-b {
  color: blue;
}

p#section-b {
  color: white;
}
<div id="section-a">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

<div id="section-b">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

CodePudding user response:

First you should use the semantic <section>-tag for sections instead of div's. Then your selector is wrong. h2#section-a looks for an h2 elment with the id section-a. What you looking for as selector should be: #section-a h2:

h2 {
  font-family: 'Wellfleet', cursive;
}

p {
  font-family: 'Roboto Mono', monospace;
}

#section-a h2 {
  color: red;
}

#section-a p {
  color: black;
}

#section-b h2 {
  color: blue;
}

#section-b p {
  color: white;
}


/* added for visualisation purpose */
body {
  background-color: grey;
}
<div id="section-a">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

<div id="section-b">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

CodePudding user response:

Change the order of your css selectors.

From p#section-a

To #section-a p

h2 {
  font-family: 'Wellfleet', cursive;
}

p {
  font-family: 'Roboto Mono', monospace;
}

#section-a h2 {
  color: red;
}

#section-a p {
  color: black;
}

#section-b h2 {
  color: blue;
}

#section-b p {
  color: white;
}
<div id="section-a">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

<div id="section-b">
  <h2>LOREM</h2>
  <p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> consequat.</p>
</div>

  • Related