Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS first-child and last-child don't work when used on the same element

Tags:

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?

like image 859
Atadj Avatar asked Aug 23 '12 14:08

Atadj


2 Answers

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.

like image 123
BoltClock Avatar answered Sep 30 '22 02:09

BoltClock


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; } 
like image 37
fstorr Avatar answered Sep 30 '22 00:09

fstorr