Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selecting First Child

Im still trying to figure out how to properly use my nth, first, and last child selectors. Thanks for your patience.

If my markup is like this:

<div class="the-wrapper">
    <table class="the-table">
       <!-- the table -->
    </table>

    <table class="the-table">
       <!-- the table -->
    </table>
</div>

How can I select the last <table class="the-table"> to apply a margin?

I thought I could select it like this: .the-wrapper .the-table:last-child { /* css */ } but this does not work. What am I missing? Thank you!

EDIT


Sorry everyone I printed my markup incorrectly... The correct markup is above

like image 874
Dude Avatar asked Aug 25 '26 04:08

Dude


2 Answers

The + is used to select "siblings" elements. (siblings in the sense of being childs of the same parent) http://jsfiddle.net/Lhmjq/

You can't use nth-child or last-child for this; as the name say, is for childs, and unless you put a parent, you can't do it.

Here is an example with a parent: http://jsfiddle.net/Lhmjq/2/ In this case, is done with last-child


(updated to your new code) Here is a tiddle: http://jsfiddle.net/Lhmjq/4/

.the-wrapper .the-table:last-child {
    color: blue;
}

Updated with your new code: http://jsfiddle.net/Lhmjq/4/

like image 55
chris-l Avatar answered Aug 26 '26 17:08

chris-l


.the-wrapper .the-table:last-child { /* css */ }

The previous code should select the last table in the wrapper. The targeting for structural pseudo classes can be confusing. The pseudo classes are defined in regards to it's direct parent. For instance, say you have a list of elements:

<ul class="target-me">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

and you want to target the last li in the list. Your CSS would be:

.target-me > li:last-child { color: red; }

You can also use the pseudo selectors to target numbered items from the position in the DOM, say I want to target the second element:

.target-me > li:nth-child(2) { color: red; }

You can also use these pseudo selectors in a selector hierarchy.

.target-me > li:first-child span { ... }

You can also chain pseudo selectors:

.target-me > li:first-child:hover { ... }

In conjunction with a polyfill like Selectivizr you can use these selectors on all browsers. I hope this helps!

like image 31
Matthew R. Avatar answered Aug 26 '26 18:08

Matthew R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!