/ CSS, FRONT-END

How to add a style to first element in css?

Question

There is a html code as below.

<div class="ctr-1">
    <h3>Title</h3>
    <div class="ctr-2">
        <h3>Title</h3>
    </div>
</div>

And I wanna apply a style to first element <h3> with .ctr-1 h3:first-child{ display:none; }, however, it will apply to all <h3>, I only want the first <h3> has this style.

Answer

:first-of-type and :nth-of-type() might be helpful here.

:first-of-type

The :first-of-type CSS represents the first element of its type among a group of sibling elements. See example below.

<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
p:first-of-type {
  color: red;
}

In this way, Paragraph 1 will be red.

:nth-of-type()

The :nth-of-type() CSS matches one or more elements of a given type, based on their position among a group of siblings.

<div>
  <div>This element isn't counted.</div>
  <p>1st paragraph.</p>
  <p>2nd paragraph.</p>
  <div>This element isn't counted.</div>
  <p>3rd paragraph.</p>
  <p>4th paragraph.</p>
</div>
/* Odd paragraphs */
p:nth-of-type(2n+1) {
  color: red;
}

/* Even paragraphs */
p:nth-of-type(2n) {
  color: blue;
}

/* First paragraph */
p:nth-of-type(1) {
  font-weight: bold;
}

In this way, 1st paragraph. and 3rd paragraph. will be red, also 2nd paragraph. and 4th paragraph. will be blue.

Besides that, 1st paragraph. will be bold as well.

Reference


This is the end of post