Last-child style over-rides first-child style when

2019-04-20 04:32发布

问题:

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.

回答1:

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/



回答2:

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.



回答3:

Why not put the border radius on the container instead?

ul,li { margin:0; padding:0; list-style:none; }
ul { border-radius: 10px; overflow:hidden }
a { display:block; margin-bottom:2px; padding:3px; background-color:#f00 }
ul li:last-child a {
 margin: 0;
} ​

http://jsfiddle.net/BanEg/



回答4:

You can also use auto insead of 0px values. Ex. (LESS):

&:first-child{
    .border-radiuses (5px, auto, auto, 5px);

}
&:last-child{
    .border-radiuses (auto, 5px, 5px, auto);
}