Explain Codes LogoExplain Codes Logo

How do I set vertical space between list items?

html
responsive-design
css
best-practices
Alex KataevbyAlex Kataev·Nov 4, 2024
TLDR

To create vertical space between list items, you directly adjust the <li> elements using CSS margin:

/* Mother always said, "mind the gap!" */ li { margin-bottom: 10px; }

This simple piece of CSS adds a 10px gap below each list item. Feel free to tweak the pixel value to your heart's content.

Skip the last gap: Pseudo-class magic

While our fast answer does the trick, we might not need extra space after the final item. This is where CSS :not() pseudo-class comes into play.

/* To last child: "You're not special!" */ li:not(:last-child) { margin-bottom: 10px; }

Alternatively, the adjacent sibling selector can achieve similar results in just one line:

/* Psst... let's skip the last item */ li + li { margin-top: 10px; }

Debugging aid: visual border

During development, it's handy to visually confirm the margins. Applying a temporary border can help:

/* Red: the color of debugging */ li { border: 1px solid red; margin-bottom: 10px; }

Remember to remove the border once you've achieved the perfect spacing.

Line-height: The unsung hero

The line-height property also plays a key role in determining the appearance of list items. It fine-tunes the space between text lines within each item:

/* "Give the text some room to breathe," they said */ li { line-height: 1.6; }

A well-adjusted line-height in sync with the margin can make your list items more appealing.

Backward compatibility: Making old browsers happy

Working with older browsers or considering different browser compatibility? Then you might need to call in our JavaScript back-up:

/* When CSS is too modern for old browsers */ if ( /* condition checking older browser */ ) { var listItems = document.querySelectorAll('li'); for (var i=0; i < listItems.length - 1; i++) { listItems[i].style.marginBottom = '10px'; /* Good ol' JavaScript to the rescue! */ } }

Though it's wiser to let JavaScript stick to its duties and let CSS handle the styling.

After list: Space matters everywhere!

Consider giving some breathing space after the list as well. It ensures your text and design flow smoothly.

/* And... relax! */ ul { margin-bottom: 20px; }

Balancing these values creates a harmonious rhythm throughout your content.