Not to Select the First Child in CSS
-
Use the
:not(selector)
Selector Not to Select the First Child in CSS -
Style the First Child Individually Using the
:first-child
Selector Not to Select the First Child in CSS
In this article, we will learn how to utilize CSS Selectors not to select the first child.
Use the :not(selector)
Selector Not to Select the First Child in CSS
We can use the :not(selector)
selector to select every other element that is not the selected element. So, we can use the selector not to select the first child in CSS. We can use :first-child
as the selector in the :not(selector)
selector. In this way, we can apply styles to all the descendants of an element except the first one. Here, in browsers with CSS Selectors level 3 are supported, we can use the :not
selector.
For example, create the body
tag in HTML. Then, write three p
tags and write some content of your choice between the tags. In CSS, select body p:not(:first-child)
and set the color
to red
.
Here, in the snippet below, we can see that the body contains paragraphs, and all of them have their font color set as red except the first one. Thus, we can select all the children except the first child and apply styles. The :not
selector, however, has certain limitations ( such as it can only process simple selectors as argument).
Code Example:
<body>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</body>
body p:not(:first-child) {
color: red;
}
Style the First Child Individually Using the :first-child
Selector Not to Select the First Child in CSS
We can set specific rules that override the rule previously set using the :first-child
selector. By this technique, we can style all the children except the first child. Overriding the styles using the :first-child
selector will make the first child appear different from the other children.
For example, use the same HTML structure as in the first method. In CSS, select the p
tag and set the color
to blue. Next, select the first child as body p:first-child
and then set the color
to black
.
Here, the default style for the paragraphs except the first one is set as color: blue
, whereas it is overridden by color: black
using the :first-child
selector. Thus, we can use the :first-child
selector not to select the first child.
Code Example:
p{
color:blue;
}
body p:first-child {
color: black;
}
<body>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</body>