Part 4—CSS Preprocessing

23 Nested styles

We can nest selector to put related style definition into groups.

An Scss example of nested selectors.

.page {
  p {
    margin: 1em 0;
  }
  .row {
    width: 100%;
  }
  &>div {
    padding: 10px;
  }
}

This scss will compiled into the following css.

.page p {
  margin: 1em 0;
}
.page .row {
  width: 100%;
}
.page>div {
  padding: 10px;
}

The Scss edition of our minimal grid system.

.row {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px;

  @media screen and (min-width: 500px) {
    overflow: auto;
  }

  .row {
    width: auto;
    max-width: none;
    margin: 0 -10px;
  }
}

.col {
  padding: 0 10px;
  width: 100%;

  @media screen and (min-width: 500px) {
    float:left;
  }
}


/* Navigation */
nav li {
  width: 100%;
  padding: 5px;

  @media screen and (min-width: 500px) {
    width: 33.33%;
    float: left;
  }

  a {
    background: #efefef;
    display: block;
    padding: 15px 0px;
    text-align: center;
  }
}

@media screen and (min-width: 500px) {
  .one {
    width: 25%;
  }
  .two {
    width: 50%;
  }
  .three {
    width: 75%;
  }
  .four {
  }
}

The compiled CSS from the Scss.

.row {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px; }
  @media screen and (min-width: 500px) {
    .row {
      overflow: auto; } }
  .row .row {
    width: auto;
    max-width: none;
    margin: 0 -10px; }

.col {
  padding: 0 10px;
  width: 100%; }
  @media screen and (min-width: 500px) {
    .col {
      float: left; } }

/* Navigation */
nav li {
  width: 100%;
  padding: 5px; }
  @media screen and (min-width: 500px) {
    nav li {
      width: 33.33%;
      float: left; } }
  nav li a {
    background: #efefef;
    display: block;
    padding: 15px 0px;
    text-align: center; }

@media screen and (min-width: 500px) {
  .one {
    width: 25%; }

  .two {
    width: 50%; }

  .three {
    width: 75%; } 
}

License

Nested styles Copyright © by makzan. All Rights Reserved.

Share This Book

Notice: 2nd edition update is work-in-progress. See update logs for details.