user
In CSS how to select the first <p> tag of an element with a given class name?
alphonsio

The best way to select the first <p> tag of a parent element with a given class name is to use a combination of class selectors and the :first-of-type pseudo-classes. Here’s how you can achieve this:

.container p:first-of-type {
    /* Your styles here */
}

In CSS, you can select the first <p> tag within an element that has a specific class name using a combination of class selectors and the :first-child or :first-of-type pseudo-classes.

  • Use :first-child if the <p> element is the absolute first child in the container.
  • Use :first-of-type if the <p> element is the first <p> among its siblings but not necessarily the very first child.
    Choose the one that matches your particular layout and structure requirements.

Here’s how you can achieve this:

Using :first-child Pseudo-class

The :first-child pseudo-class targets the first child of its parent element, which must be a <p> tag in this case.

.container p:first-child {
    /* Your styles here */
}

Using :first-of-type Pseudo-class

The :first-of-type pseudo-class targets the first <p> element among its siblings, regardless of its type.

.container p:first-of-type {
    /* Your styles here */
}

Examples

Assuming you have HTML like this:

<div class="container">
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>
<div class="container">
    <div>Not a paragraph</div>
    <p>Third paragraph</p>
</div>

Example with :first-child

If you want to target only the first <p> element that is also the first child of its parent:

.container p:first-child {
    color: red;
}

In this case, only the first <p> in the first .container will be styled red :

Example with :first-of-type

If you want to target the first <p> element within each .container, regardless of its position among siblings:

.container p:first-of-type {
    color: blue;
}

Both the first <p> in both .container elements will be styled blue, regardless of other types of elements that may precede them within the same parent: