I just noticed that CSS :first-child
and :last-child
don't work when used on the same element. Only one is used. I'm wondering why is that and if there is any workaround to that in CSS? It seems like CSS bug to me - first element can be also last element.
I couldn't find anything in Google on that subject. Each tutorial assumes that there will be at least 2 elements.
I'm looking for something like: "first child is also last child" selector. Does it exist?
I'm wondering why is that and if there is any workaround to that in CSS? It seems like CSS bug to me - first element can be also last element.
It's not a bug. It's how the cascade works: if an element is both the first child and the last child, then if you have :first-child
and :last-child
in separate rules and they both match the same element, then anything in the later declared or more specific rule will override the other.
You can find an example of this behavior here, with the border-radius
shorthand property, and workarounds that include using the component properties instead of the shorthand, as well as specifying a separate rule altogether using one of the following selectors...
I'm looking for something like: "first child is also last child" selector. Does it exist?
Literally, you would chain both pseudo-classes like this, which works fine:
:first-child:last-child
However there exists a special pseudo-class that acts the same way:
:only-child
The main difference (in fact, the only difference) between these two selectors is specificity: the first one is more specific as it contains one additional pseudo-class. There is no difference even in browser support, as :last-child
and :only-child
are both supported by the exact same versions of each browser.
I realise I'm massively late to this, but you can also use is CSS's :first-of-type
and :last-of-type
. For example:
<blockquote> <p>Some text you want to quote</p> </blockquote>
This CSS will add quotes to the paragraph:
blockquote{ quotes: "“" "”" "‘" "’"; } blockquote p:first-of-type:before{ content:open-quote; } blockquote p:last-of-type:after{ content:close-quote; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With