Pooks
Pooks

Reputation: 13

In a 3 column grid of a varying number of elements, how to select only the elements that appear on the last line using CSS

Image example: 3 column grid with 1, 2 or 3 elements on the last line

Is it possible to select only the elements that appear on the last line using only CSS? The number of elements in the grid will vary. Here is an example of how to do it with a 2 column grid: Select last child when odd, 2 last childs when even

<h2>6 elements</h2>
<ul>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li style="background: pink;">hello ------</li>
    <li style="background: pink;">hello ------</li>
    <li style="background: pink;">hello ------</li>
</ul>
<h2>7 elements</h2>
<ul>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li style="background: pink;">hello ------</li>
</ul>
<h2>8 elements</h2>
<ul>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li>hello ------</li>
    <li style="background: pink;">hello ------</li>
    <li style="background: pink;">hello ------</li>
</ul>

Here is an example of the HTML on jsfiddle: https://jsfiddle.net/rm9te941/

Thanks

Upvotes: 0

Views: 44

Answers (1)

xpy
xpy

Reputation: 5621

I also said 'No' but also 'Why not?'

You just have to select all the elements after the element that is nth-child(3n) but also :nth-last-child(-n + 4) which means:

Every element that is both after an element that is a multiple of three and is in the last three elements

li:nth-last-child(-n + 4):nth-child(3n) ~ li {
  background: #000;
}

I also made a fiddle

The funny thing is that this will work for every number of columns providing you change 3 with the number of your columns.

Upvotes: 1

Related Questions