[CSS] Siblings selector

For example, we have current html code:

    <main class="grid-wrap">
      <div class="grid">
        <span>One column default</span>
      </div>

      <div class="grid">
        <span>Half column 1</span>
        <span>Half column 2</span>
      </div>

      <div class="grid">
        <span>3-col 1</span>
        <span>3-col 2</span>
        <span>3-col 3</span>
      </div>

      <div class="grid">
        <span>4-col 1</span>
        <span>4-col 2</span>
        <span>4-col 3</span>
        <span>4-col 4</span>
      </div>
    </main>

We have mulit .grid class, let's say we want to have some margin between each .grid element, but not affecting the first .grid element. we can use Siblings Selector:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax($minWidth, 1fr));
  grid-gap: $gridGap;

  & + .grid {
    margin-top: $gridGap;
  }
}

It means, beside the very first .grid element, apply css to all the rest element which have .grid class.

Layouting element like this way, we can safely add padding to the outmost container, without worrying the first .grid element's margin will affect the layout.

原文地址:https://www.cnblogs.com/Answer1215/p/12956752.html