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

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?

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.


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;
}

Need Your Help

What is the difference between rhino-mocks stub and expect

mocking rhino-mocks stub stubbing expectations

What is the difference between rhino-mocks stub and expect here: Looks to me that they behave exact the same?

Timing Delays in VBA

vba timer wait pause timedelay

I would like a 1 second delay in my code. Below is the code I am trying to make this delay. I think it polls the date and time off the operating system and waits until the times match. I am havi...