Targetting specific css tags

  • Post author:
  • Post category:CSS
  • Post comments:0 Comments
h2 {
  color: blue;
  font-size: 40px;
  margin: 50px; 
  background-color: yellow; 
  text-align: center; 
}
p {
  color: #55CC77;
  background-color: rgb(120,20,56);
}
h3 {
  color: pink;
  font-size: 20px;
  margin: 0px;
  background-color: blue;
}
<!DOCTYPE html>
<html>
  <head>
    <title>My website</title>
   <meta charset="UTF-8">
   <link rel="stylesheet" a href="style.css">
  </head>
  <body>
    <div>
      <section>
        <h2>Latest Deals</h2>
        <h3>See latest holiday deals here</h3>
        <article>
          <h4>Holiday 1</h4>
          <h3>See holiday break number 1</h3>
          <p>A lovely break in spain</p>
        </article>
      </section>
    </div>
  </body>
</html>

In the above we’ve styled the h3 tags. But how do we target the second h3 tag specifically.

From the html code we can see the second h3 tag is inside an opening and closing <article> tag so we can use those to target spcifically that particular h3 tag. Let’s modify the css.

h2 {
  color: blue;
  font-size: 40px;
  margin: 50px; /* margin of 50px around h2 text */
  background-color: yellow; /* yellow background */
  text-align: center; /* center the text */
}
p {
  color: #55CC77;
  background-color: rgb(120,20,56);
}
h3 {
  color: pink;
  font-size: 20px;
  margin: 0px;
  background-color: blue;
}

article h3 {
  color: black;
  font-size: 20px;
  margin: 0px;
  background-color: orange;
}

We can see from the last block above, any h3 tag that is inside and article tag will be treated the the css inbetween the {}.

We see this now on our website. We’ve managed to target the h3 tag that we wanted.


In practice though, we generally make use of ‘class’ to target individual tags. Below we make a class “holiday_break_title” in the css. Note, the class cannot have white spaces inbetween.

h2 {
  color: blue;
  font-size: 40px;
  margin: 50px; /* margin of 50px around h2 text */
  background-color: yellow; /* yellow background */
  text-align: center; /* center the text */
}
p {
  color: #55CC77;
  background-color: rgb(120,20,56);
}
h3 {
  color: pink;
  font-size: 20px;
  margin: 0px;
  background-color: blue;
}

.holiday_break_title {
  color: black;
  font-size: 20px;
  margin: 0px;
  background-color: orange;
}
<!DOCTYPE html>
<html>
  <head>
    <title>My website</title>
   <meta charset="UTF-8">
   <link rel="stylesheet" a href="style.css">
  </head>
  <body>
    <div>
      <section>
        <h2>Latest Deals</h2>
        <h3>See latest holiday deals here</h3>
        <article>
          <h4>Holiday 1</h4>
          <h3 class="holiday_break_title">See holiday break number 1</h3>
          <p>A lovely break in spain</p>
        </article>
      </section>
    </div>
  </body>
</html>

Creates the same looking page:

Leave a Reply