Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best usage of CSS :last-child selector in nested elements

Tags:

html

css

JSFIddle: http://jsfiddle.net/s3fnhmtz/3/

It's quite common to have margin-bottom: 20px on elements like <p> or .button as we tend to use these in page flow and these need breathing room.

But something i get stuck on quite often is removing this margin if it is the last element inside something like a <div class="panel"></div> that has some padding to it we get 20px + margin at the bottom so we end up with a bigger space at the bottom than the top.

1 fix i normally use is: .panel *:last-child *:last-child { as bad as this is it works for the most part. But in the Fiddle you can see if you was using something like a <dt> it falls apart a bit.

I can't realistically go through and list every element that could possible be last so is there a better foolproof way to fix this issue?

like image 992
Dan Gamble Avatar asked Oct 23 '25 17:10

Dan Gamble


1 Answers

While still valid, a lot of the answers are missing the point of your question, which is a more concise method to recursively drill down through the last children.

See this answer here: Select recursive :last-child. Possible?

So your only recourse may be to drill down with the wildcard selector.

.panel.two > *:last-child,
.panel.two > *:last-child > *:last-child,
.panel.two > *:last-child > *:last-child > *:last-child {
    margin-bottom: 0;
}

You may be able to create a recursive-check mixin using SASS, but I don't believe the elegant single attribute recursive application exists. :(

like image 162
Plummer Avatar answered Oct 26 '25 08:10

Plummer