How to style every element which has an adjacent item right before it?

Technology CommunityCategory: CSSHow to style every element which has an adjacent item right before it?
VietMX Staff asked 3 years ago

Use The Lobotomized Owl Selector:

* + * {
  margin-top: 1.5em;
}

The idea is that only elements that have a previous sibling inside a container get margin on top.

Another example:

<div class="container">
  <div>Box 1</div>
  <div>Box 2
    <div>Sub-box 1</div>
    <div>Sub-box 2</div>
  </div>
  <div>Box 3</div>
</div>

Css:

* + * {
  margin-top: 0.5em;
}

html, body {
  height: 100%;
}

body {
  font-family: "Roboto", san-serif;
  margin: 0;
  overflow: hidden;
}

.container {
	background: #ccc;
  min-height: 100%;
  padding: 2em;
}

.container div {
  background: #fff;
  border: 2px dashed #666;
  padding: 2em;
  width: auto;
}

.container div:nth-child(2) > div {
	background: #ccc;
}