Quickest way to add space between child elements (without adding space around them)
Ever had a navigation menu and wanted to add space only between the navigation items and not around it? Like this 👇
The usual method
The usual way of doing something like this is to add margin
/ padding
/ border
for every child and then negate that using :last-child
selector.
The alternate method
While the usual method works great, we can achieve the same with much lesser code using the adjacent sibling selector. Check this out!
How it works
Here li + li
is an adjacent sibling selector. In plain English, it means, "Select all li
elements that have an li
element just before them as a sibling".
So the selector ul > li + li
helps us select all the li
elements within ul
except for the first one.
Now that we have all the li
elements selected except for the first one, we can add a margin-top
to them.
You can do the same to different types of elements too. Let's say you have a heading, image, paragraph and a div
element within a section:
If you want to space out all these elements equally without adding space around them, you can do this!
Since *
is the universal selector, the type of element does not matter. This will select all immediate children of section
element except for the first child. Isn't that convenient?
And of course, this works for horizontally placed elements too. Demo for inline elements
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.