CSS Spacing

Clever CSS Spacing Between Elements with + Selector

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…

CSS Spacing with + selector

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 🙂

Leave a Comment

You want to leave a comment? Sweet! Please do so, but keep in mind that all comments are moderated and rel="nofollow" is in use. So no fake comment or advertisement will be approved. And don't worry, your email address won't be published. Thanks!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>