Ashwin
Ashwin

Reputation: 12411

Is there a way in css to select second last child?

Need to ensure browser compatibility as well (should work in IE8)

I came across - :nth-last-child(2)
But it is not browser compatible as it is a css3 selector.

Also I came across a tip to get 2nd, 3rd, 4th child as - td:first-child + td + td
But no way of reversing like
td:last-child - td
to get second last child.

I don't want to use jquery.
Is applying class to the second last element is only option ?

Upvotes: 4

Views: 5854

Answers (6)

XIMRX
XIMRX

Reputation: 2170

If :nth-last-child(2) is not working for you:

You can count all children divs of parent:

var totalChildDivs = jQuery('.parent div').length;

And then target the second last child:

jQuery('.parent div')[totalChildDivs-1].css("background: red;");

Upvotes: 0

Mohammed Javed
Mohammed Javed

Reputation: 876

Use this it is simple in CSS:

:nth-last-child(2)

Upvotes: 0

user2843596
user2843596

Reputation:

nth-last-child Syntax:

:nth-last-child(N) { } N can be:

number - Any integer (1, 2, 10, etc.). This will match the child in that exact position, counting up from the bottom of the parent. expression An algebraic expression of the form an+b to allow you to match on more complex combinations odd - Matches every other child, starting with the last one. even - Matches every other child, starting with the second to last one.

Upvotes: 1

ScottS
ScottS

Reputation: 72261

Only Because You Imply You Are Working with a Table

You are not clear on what you want to do to the second to last group, however, only because your example is referring to table cells, I offer this possible solution--using <col /> styling.

It would require you to know the number of columns. Here is an explanation. It has very severe limitations on what styles can be set (though it does work in IE8). Here is an example fiddle, which has the following example:

HTML

<table>
    <col span="2"/>
    <col class="secondToLast"/>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>

CSS

.secondToLast {
    border: 1px solid blue;
    background-color: cyan;
    width: 100px;
}

Upvotes: 1

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201518

Under the conditions specified, applying class (or id) to the second last element is only option.

Upvotes: 2

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

The CSS3 nth-last-child is probably the way to go, since support should become more and more common.

Failing this, you could simply add a CSS class to the element in the markup eg:

<tr>
  <td>...</td>
  <td class = "penultimate">...</td>
  <td>...</td>
</tr>

Upvotes: 4

Related Questions