Apply CSS only if the element is followed by another element

One thing I was faced with when working on CSS with dynamic data is to apply a padding only if the element had other elements following it. An example would be when you have a list. If you have only one <li> in the list, you don’t want to apply any padding. However, if you have multiple elements, you want to apply a padding between the different <li>.

Here is how to do it using CSS:

li + li {
    padding-top: 20px;
}

The code above will apply the padding on the second element. So if you have one <li> it won’t apply. If you have two, it will apply to the second. If you have three, it will apply to the elements two and three. And so on…

Demo on custom HTML with three cases

Here is a demo of the code above on different kinds of lists. I also added a red color, so you can clearly see when the padding is added.

Fist list with two elements

  • Test
  • Test

Second list with multiple elements

  • Test
  • Test
  • Test

Third list with one element

  • Test

The code I used for the demo:

<style>
    li.item-test + li.item-test {
    padding-top: 20px;
    background-color: red;
}
</style>

<p>Fist list with two elements</p>
<ul>
    <li class="item-test">Test</li>
    <li class="item-test">Test</li>
</ul>

<p>Second list with multiple elements</p>
<ul>
    <li class="item-test">Test</li>
    <li class="item-test">Test</li>
    <li class="item-test">Test</li>
</ul>

<p>Third list with one element</p>
<ul>
    <li class="item-test">Test</li>
</ul>

Hope this would help.

More resources

coding games

Women in tech

TheTrendyBrand