Let’s say you have a list of elements, and you want to elegantly add a bit of space between them so that they don’t appear too clumped together…
Well, it’s pretty easy if you have the right tool: the +
CSS selector!
.fruit-container div+div { margin-left: 30px; }
You don’t need to use a margin
or padding
on each element and add a first-item
or last-item
class to remove the extra spacing, the +
selector takes care of everything.
How does it work ?
Let’s take an example: if you have div + p
in your CSS, it will select the first <p>
element that is placed immediately after <div>
elements. That’s why you add a margin-left
(and not a margin-right
) to the items you want to space up.
Indeed this one-line magic trick works for all kinds of elements (images, div, span, li, …). For more CSS Selectors, have a look at this extensive list.
What is your favorite underrated CSS selectors, and how do you use it?
I hope it helps, feel free to buy me a coffee (or tea) to support the blog 🙂