sass - nested rule

Posted by TaosBill on Wed, 18 Dec 2019 21:02:12 +0100

I. Basic nesting rules

A given rule block can contain attributes like normal CSS and nest other rule blocks

#content {
  article {
    h1 { color: #333 }
    p { margin-bottom: 1.4em }
  }
  aside { background-color: #EEE }
}
 /* After compilation */
#content article h1 { color: #333 }
#content article p { margin-bottom: 1.4em }
#content aside { background-color: #EEE }

In most cases, this simple nesting is OK, but not in some scenarios. sass will connect the parent selector (ාcontent) to the front edge (article and aside) of the child selector through a space to form (񖓿content article andාcontent aside) when solving a nested rule. This is called the descendant selector in CSS

Identifier of the parent selector&

1. Do not want to connect in the way of next generation selector, such as hover

article a {
  color: blue;
  &:hover { color: red }
}

2. Add selector before parent selector

#content aside {
  color: red;
  body.ie & { color: green }
}

/*After compilation*/
#content aside {color: red};
body.ie #content aside { color: green }

Nesting of group selectors

.container h1, .container h2, .container h3 { margin-bottom: .8em }

IV. sub combination selector and same layer combination selector: >, + and~

In this scenario, you don't even need to use the parent selector identifier&

article {
  ~ article { border-top: 1px dashed #ccc }
  > section { background: #eee }
  dl > {
    dt { color: #333 }
    dd { color: #555 }
  }
  nav + & { margin-top: 0 }
}

article ~ article { border-top: 1px dashed #ccc }
article > footer { background: #eee }
article dl > dt { color: #333 }
article dl > dd { color: #555 }
nav + article { margin-top: 0 }

V. nested properties

The rule of nesting attributes is as follows: disconnect the attribute name from the underlined part, add a colon after the root attribute: immediately follow a {} block, and write the sub attribute part in this {} block.

nav {
  border: {
  style: solid;
  width: 1px;
  color: #ccc;
  }
}

nav {
  border-style: solid;
  border-width: 1px;
  border-color: #ccc;
}

For abbreviated forms of attributes, you can even nest them like the following to indicate exception rules:

nav {
  border: 1px solid #ccc {
  left: 0px;
  right: 0px;
  }
}

 

Topics: Attribute IE sass