Labanino
Labanino

Reputation: 3960

Targetting a class with :last-child

I have a class .side-box { margin: 0 10px 10px 0; } and what I'm trying to do is target the last .side-box in the DOM and apply margin-right: 0; to it with no jquery and no extra class to overwrite margin-right. In this way I have only a padding: 10px; wrapping the three boxes.

I tried:

.side-box:nth-child(2) {
     margin-right: 0;
}

and

.sidebars:last-child {
     margin-right: 0;
}

but didn't work. What am I doing wrong? Thanks.

FIDDLE HERE: http://jsfiddle.net/qL7wx5pp/

Upvotes: 0

Views: 38

Answers (2)

Sinstein
Sinstein

Reputation: 909

If you read about last-child here is says:

The :last-child selector matches every element that is the last child of its parent.

I have highlighted the last child of its parent because that is what is causing your issue.

You have not applied the margin to the sidebars but to the side-box So this wont do what you want.

.sidebars:last-child {
     margin-right: 0;
}

Now to target the correct side-box you need to realise how your DOM is structured.

You have a parent wrapper with 3 child sidebars To target the last side-box, you need to target the last sidebars

Hence selecting sidebars:last-child is the correct target div. But the margin needs to be reset on the side-box div that is again a child of the last sidebars div

So the correct selector would be:

sidebars:last-child > side-box

side-box that is a child of the last child sidebars. See demo here

Upvotes: 2

Leroy
Leroy

Reputation: 247

You've almost got it. You want to select the last sidebars and then get the side-box inside. Something like this:

.sidebars:last-child > .side-box

http://jsfiddle.net/qL7wx5pp/2/

Upvotes: 1

Related Questions