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

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

主站蜘蛛池模板: 大丰市| 明星| 曲靖市| 米脂县| 白水县| 广河县| 乌什县| 海南省| 蒲城县| 安阳市| 南雄市| 威海市| 三都| 金川县| 扶绥县| 西宁市| 石景山区| 汉阴县| 绵阳市| 泗洪县| 营山县| 永年县| 马尔康县| 吉首市| 巍山| 兰坪| 科尔| 章丘市| 镇赉县| 珲春市| 布尔津县| 舒兰市| 高要市| 广安市| 会理县| 陕西省| 胶南市| 台北市| 洮南市| 乃东县| 油尖旺区|