官术网_书友最值得收藏!

Creating more intuitive code and making inheritance clear

While HTML code already has a nested structure of HTML elements, CSS code has no nesting. Sass extends CSS with nesting, which enables you to create selectors that follow the same nested structure as your HTML.

Getting ready

Read the Installing Sass for command line usage recipe of Chapter 1, Getting Started with Sass, to find out how to install Ruby Sass.

How to do it...

Learn how to make your code more intuitive by performing the steps shown beneath:

  1. Create a Sass template called main.scss that will contain the following SCSS code:
    // scss-lint:disable ColorKeyword
    
    $link-color: black;
    
    p {
      font-size: 1em;
      a {
        color: $link-color;
      }
    }
  2. Compile the main.scss file from the previous step into CSS code by running the following command in your console:
    sass main.scss
    
  3. You will find that the CSS code outputted to your console will look like that shown here:
    p {
      font-size: 1em; }
      p a {
        color: black; }

How it works...

Web browsers use the hierarchy of your HTML structure to calculate CSS property values that have not been explicitly set. Consider an HTML structure like that shown here:

<div>
  <h2>blue</h2>
</div>

Here, the font color set by the color CSS property of the h2 HTML element inherits its value from the div HTML element. Note that the color CSS property has a default value of inheritance.

Now, you can use an SCSS code like that shown here to visualize this inheritance:

div {
  color: blue;

  h2 {
   font-size: 1.3em;
  }
}

In the preceding SCSS code, it is directly clear that the nested h2 selector got a calculated color value of blue inherited from the div element.

There's more...

Although nesting your selectors can make your code more intuitive, it can equally break other things. For instance, when considering OOCSS principles, this does not allow the nesting of headings (h1 - h6). Headings are considered to be built-in objects in OOCSS, so their appearance should be consistent across an entire website. You can read more about OOCSS in the Applying the OOCSS, SMACSS, and BEM methodologies recipe of this chapter.

You should restrict the levels of nesting in your SCSS code. If you apply too much nesting to your selectors, your CSS will get broken for every change in your HTML structure. Read more about this topic in the Avoiding nested selectors too deeply for more modular CSS recipe of this chapter.

See also

主站蜘蛛池模板: 平湖市| 英吉沙县| 鸡东县| 邯郸市| 莱州市| 秭归县| 郁南县| 古蔺县| 永仁县| 正镶白旗| 天台县| 南投县| 衡东县| 连城县| 馆陶县| 织金县| 电白县| 额济纳旗| 大兴区| 长汀县| 固原市| 兰考县| 平度市| 电白县| 芦山县| 安龙县| 永修县| 金平| 北海市| 恩平市| 凤山县| 永兴县| 兴国县| 和政县| 珠海市| 石嘴山市| 尉犁县| 常熟市| 巴南区| 岚皋县| 屯留县|