How to style the first child of an element differently in CSS

Arif Billah Babu

         

  CSS



Image not found!!

In CSS, you can use the :first-child pseudo-class to select and style the first child of an element. Here's an example:

css
/* Selects the first child of an element and styles it */
.parent-element :first-child {
     /* Your styles go here */
     color: red; font-weight: bold;
}

In the example above, replace .parent-element with the actual class or ID of the parent element you want to target. The styles inside the curly braces will be applied only to the first child of that parent element.

Here's a simple HTML example for better understanding:

html
<div class="parent-element">
        <p>First child - This will be styled differently</p>
        <p>Second child</p>
        <p>Third child</p>
</div>

In this example, only the first <p> element inside the .parent-element will be styled according to the rules specified in the CSS.

Remember that the :first-child pseudo-class selects the first child regardless of its type. If you want to select the first child of a specific type (e.g., the first <p> element), you can use the element type along with the :first-child pseudo-class:

css
.parent-element p:first-child { /* Your styles for the first <p> element go here */ }

This will only select the first <p> child of the .parent-element for styling.