In CSS, what is the difference between cascading and inheritance?

前端 未结 2 786
南笙
南笙 2020-11-29 08:20

In CSS, what is the difference between cascading and inheritance?

Or are both the same thing?

2条回答
  •  天命终不由人
    2020-11-29 08:56

    To understand the difference between inheritance and cascading let's understand both of them with example.

    Inheritance is a way of propagating property values from parent elements to their children, let's have a very simple example here.

    .parent{
    font-size:20px;
    line-height:150%;
    }
    .child{
    font-size:25px;
    }
    

    From the above example, we are going to determine what the line-height of the child element will be. We all know that every CSS property must have a value, even if neither we, the developer nor the browser do specify it. In that case, there's no cascaded value, right? So when processing a certain property for a certain element, such as line-height the first question that the CSS engine asks is if there is a cascaded value, if so then of course, that's the value that's used. Now if there's no cascaded value then the next question is if the property can be inherited, that depends on each property, there are some properties that are inherited and others are not. In the case of line-height, that property gets inherited as we can see from the property specification.

    https://developer.mozilla.org/en-US/docs/Web/CSS/line-height

    So if a property is inherited, then the value of that property becomes the computed value of its parent element. It's very important to note that the value that gets inherited is not simply 150%, but the computed value. In this case, that's 150% of 20 pixels, which is 30 pixels. So the line-height of the child element will also be 30 pixels, not 150% of the 25-pixel font size. Now if it's a property that's not inherited like for example, padding, then the specified value will become the initial value which is also specific to each property. In the case of padding that's just zero pixels.

    Now Cascading is the process of combining different stylesheets and resolving conflicts between different CSS rules and declarations when more than one rule applies to a certain element. Because as you probably already know a declaration for a certain style property like font size can appear in several stylesheets and also several times inside one single stylesheet.

    If you want to read in detail about cascading in CSS just read my other answer about cascading.

    What is the meaning of "cascading' in CSS?

提交回复
热议问题