Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last-child style over-rides first-child style when only one child is available

enter image description here

ul li:first-child a {
   border-radius: 5px 5px 0 0;
}

ul li:last-child a {
   border-radius: 0 0 5px 5px;
}

When there's just once child, the last-child style over-rides the first-child style. Is there a way to apply both (since it is both the first and last child)

Am looking to achieve this with just CSS, without the aid of JS. Thanks.

like image 592
itsoft3g Avatar asked Jul 18 '12 09:07

itsoft3g


People also ask

Which nth child () selector will target only the last list item?

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.

How do I use first child and last child in CSS?

How to select an element that is the first or last child of its parent. The :first-child pseudo class means "if this element is the first child of its parent". :last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.

How do you target your second last child in CSS?

This adds a comma after each LI, an ", or" after the second to the last LI, and a period to the last LI using pure CSS with nth-last-child()::after. To affect just the second to the last LI delete the last CSS entry and set the second CSS entry's (n+3) content to empty ('').


2 Answers

Just apply your borders individually:

ul li:first-child a {
   border-top-left-radius: 5px;
   border-top-right-radius: 5px;
}

ul li:last-child a {
   border-bottom-left-radius: 5px;
   border-bottom-right-radius: 5px;
}

That way the last-applied rule doesn't override the previous rule (border-radius: 5px 5px 0 0; resets the bottom border radii back to zero).

Demo: http://jsfiddle.net/vUz5Z/5/

like image 161
Blender Avatar answered Oct 05 '22 04:10

Blender


You can use :only-child. Just add

ul li:only-child a {
   border-radius: 5px;
}

after them. It won't work in IE8 (or older), but I'm guessing its not an issue, since border-radius doesn't work in IE8 either.

Or use the border radius on the list itself ul {border-radius: 5px} if that is possible.

like image 34
Ana Avatar answered Oct 05 '22 06:10

Ana