CSS Learning Summary-cascading and inheritance

Source: Internet
Author: User

When there are multiple selectors acting on an element, which rule will eventually be applied to the element?

In fact, this is controlled by a cascade mechanism, which is also related to style inheritance (where elements derive attribute values from their parent elements).

The final style of an element can be defined in multiple places, and they interact with each other in complex forms. These complex interactions make CSS very powerful, but also make it very difficult to debug and understand.

Cascade

CSS is the abbreviation for cascading Style Sheets , which implies that the concept of cascading (cascade) is important. At its most basic level, it shows that the order of CSS rules is important, but it is more complex than that. What selectors win in a cascade depends on three factors (these are in the order of magnitude-the one in front will veto the latter):

    1. Importance (Importance)
    2. Specificity (specificity)
    3. Source code order (Origin order)
Importance

In CSS, there is a special syntax that allows a rule to always take precedence over other rules: !important . (Common when applied to the Iconfont icon property) add it to the value of the property to make the claim incredibly powerful.

Let's take a look at this example:

<p   class =   "better"  >  this is a paragraph. </P>  <p   class=   "better"   id=   "winning"  >  One selector to rule them all! </P>   
 #winning  { background-color:  red    border:  1px  solid  black     .better  {   Background-color:  gray   border:  none  !important;    p { background-color:    Blue   color:  white    padding:  5px      

This will generate the following:

Let's take a look at what happened.

    1. You can see the third rule color and padding be applied, but background-color no, why? In fact, these three cases should be applied because the rules that follow the source order often overwrite the older rules.

    2. However, the preceding rule is applied because the Ids/class selector takes precedence over the element selector.

    3. Both of these elements have class and have better attributes, but the second element has a id value of winning . Because ID specificity is higher than class (the ID is unique on a page, but many elements can have the same Class-id selector in their target), the red background color and the 1pixel black border should be applied to the second element, the first element gets a gray background color, There is no border, as specified by the class.

    4. The second element gets a red background color, but no border. Why? Because the declaration in the !important second rule, which is border: none written later, means that although the ID has a higher precedence, the declaration takes precedence over the boundary value declaration in the preceding rule.

Note : The only way to overload this !important declaration is to have a declaration that contains the same features in a later source code or a source with a higher specificity !important .

Knowing the !important existence is useful, so that when you encounter it in someone else's code, you know what it is. but! We recommend that you never use it unless you absolutely have to use it. One case where you might have to use it is when you're working in a CMS, you can't edit the core CSS module, and you really want to rewrite a style that can't be overridden in any other way. But, if you can avoid it, don't use it. !importantdebugging CSS issues, especially in large style sheets, can become very difficult because of the way the stack works.

Note that the importance of a CSS declaration depends on what style sheet it is assigned to--users can set custom style sheets to override the developer's style, such as the user may have visual impairments, and want to set the font size for all Web pages to be double normal size for easier reading.

conflicting statements will be applied in the following order, and the latter will overwrite the previous declaration :

    1. The declaration of the user-agent style sheet (for example: The browser has no other declared default style).
    2. General declarations in user style sheets (custom styles set by the user).
    3. The general declaration in the author style sheet (this is the style we set, the web Developer).
    4. Important declarations in the author style sheet
    5. Important declarations in the user style sheet

It is reasonable that the web Developer's style sheet overrides the user's stylesheet, so the design can remain predictable, but sometimes the user has a good reason to rewrite the web developer style, as described above, which can be used in the user's rules !important .

Special nature

Specialization is basically a way to measure the specificity of a selector-how many elements it can match. As the example shown above shows, the element selector has a very low specificity. The class selector has a higher specificity, so the element selector is defeated. The ID selector has even higher specificity, so the class selector is defeated. The only way to beat the ID selector is to use !important .

The amount of specificity of a selector is measured in four different values (or components), which can be thought of as thousands, hundred, 10, and bits--four simple numbers in four columns:

    1. Thousand: If the declaration is in the style attribute of the column plus 1 points (such declarations do not have selectors, so their specificity is always 1000.) Otherwise, it is 0.
    2. Hundred: Adds 1 points to this column for each ID selector contained in the entire selector.
    3. 10-bit: each containing a class selector, a property selector, or a pseudo class in the entire selector adds 1 points to the column.
    4. BITS: Each containing an element selector or pseudo-element in the entire selector adds 1 points to the column.

Note : Universal selectors ( * ), composite selectors (,, + , > ~ ') and negative pseudo-classes ( :not ) have no effect on specificity.

The following table shows a few examples. Try to get through these and make sure you understand why they have the specificity we give them.

selector thousands hundred 10-bit digit Total value
H1 0 0 0 1 0001
#important 0 1 0 0 0100
H1 + p::first-letter 0 0 0 3 0003
li > a[href*= "ZH-CN" >. inline-warning 0 0 2 2 0022
#important div > div > A:hover , in the <style> of an element; property. 1 1 1 3 1113

Before we go on, let's take a look at an example in action.
Here's the HTML we're going to use:

<divid="outer"class="Container">  <divid="inner"class="Container">    <ul>      <liclass="NAV"><ahref="#">One</a></li>      <liclass="NAV"><ahref="#">Both</a></li>    </ul>  </div></div>

The following is an example of CSS:

/ * specificity:0101 * /#outerA{  Background-color: Red;}/ * specificity:0201 * /#outer #innerA{  Background-color: Blue;}/ * specificity:0104 * /#outerDiv ul Li a{  Color: Yellow;}/ * specificity:0113 * /#outerDiv ul. NavA{  Color:  White;}/ * specificity:0024 * /Div Div Li: Nth-child(2) A: Hover {  border: 10px Solid Black;}/ * specificity:0023 * /Div Li: Nth-child(2) A: Hover {  border: 10px Dashed Black;}/ * specificity:0033 * /Div Div. Nav: Nth-child(2) A: Hover {  border: 10px Double Black;}A{  Display: Inline-block;  Line-height: 40px;  font-size: 20px;  text-decoration: None;  text-align: Center;  Width: 200px;  Margin-bottom: 10px;}Ul{  padding: 0;}Li{  List-style-type: None;}

The results we get from this code are as follows:

What's going on here? First, we are only interested in the first seven rules of this example, and as you will notice, we have included their specificity values in each comment.

    • The top two selectors are competing for the style of the background color of the link-the second to win and make the background color blue because it has an extra ID selector in the chain: its specificity value is 201:101.
    • The third and fourth selectors compete on the style of the linked text color-The second selector wins, making the text white, because a missing element selector is replaced with a class selector, which has a value of 10 instead of bits. So the specificity value is 113 and 104.
    • Selector 5-7 competes in style when hovering around a link. Selector Six is obviously lost to five, its specificity value is 23 and 24--it has one element selector missing in the chain. The selector seven defeated however at the same time five and six--it had with five the same number of sub-selectors in the chain, but an element had been swapped for a class selector. So the exclusive value of the WINS is 33:23 and 24.
Source Code Order

As mentioned above, if multiple competing selectors have the same importance and specificity, then a third factor will help determine which rule wins-the latter rule will prevail over the previous rule. For example:

{  color:blue;}/* This rule will win over the first one */{  color:red;}

The first rule in this example will win because the specificity is higher than the source code order:

/* This rule will win */.footnote{  color:blue;}{  color:red;}
A note on the blending of rules

One thing you should keep in mind when considering all of these cascading theories and what styles take precedence over other styles is that all of this happens at the attribute level-the property overrides the other properties, but you don't let the whole rule override the other rules.
When multiple CSS rules match the same elements, they are applied to the element. Only after this, any conflicting attributes are evaluated to determine which style will prevail over the other types.

Précis-writers: Overwrite occurs only if the same attribute application conflicts

Let's look at an example. First, some HTML:

<p><strong>important</strong></p>

Now some CSS styles with it:

/* specificity: 0002 */{  background-color: khaki;  color:green;}/* specificity: 0001 */{  text-decoration:underline;  color:red;}

Result:

In this case, because of the specialization, the attribute in the first rule color overrides the color value in the second. However, the attributes in the first background-color and second bars text-decoration are reflected in the strong element. You also notice that the font in this element is bold: This is the default style rule for the browser.

Inherited

CSS inheritance is the last part of the research we need to get all the information and understand what styles apply to elements.

The idea is that some attribute values applied to an element will be inherited by the child elements of that element, while others will not.

    • For example, font-family color it makes sense to do inheritance, because this allows you to easily set a site-wide base font by applying a font to an element, and then you can overwrite the font of a single element where needed. If you want to set the basic font on each element separately, it's too much trouble.

    • Again, let margin padding , border and background-image not be inherited is meaningful. Imagine that if you set these properties on a container element and inherit them to each child element, and then have to put them all on each individual element, the style/layout will appear confusing.

Which properties are inherited by default which are not inherited most common sense. If you want to be sure, you can refer to the CSS reference-each individual property page starts with a summary table with various details about the element, including whether it is inherited.

Note:
font-familyAllows you to set the font for the selected element by giving a list of the font names or the font family names in a sequential order. The value of the property is separated by commas. The browser selects the first installed font on the computer in the list, or through ' @font-face specified fonts that can be downloaded directly.

paddingThe Padding property sets the padding for an element, which refers to the space between the contents of an element and its bounds, which cannot be negative.

background-imageproperty is used to set one or more background images for an element. The image is stacked in Z-direction when it is drawn. The image that you specify first is drawn above the image that you specify later. So the first image you specify is closest to the user.

Control inheritance

CSS provides four special common property values for handling inheritance:

    • inherit: This value sets the property value applied to the selected element to be the same as its parent element.
    • initial: This value sets the property value applied to the selected element to be the same as the value set by that element in the browser's default style sheet. If a value is not set in the browser's default style sheet, and the property is naturally inherited, the property value is set to inherit .
    • unset: This value resets the property to its natural value, that is, if the property is inherited naturally, it behaves as if it were to inherit behave initial .
    • revert: If the current node does not have any styles applied, revert the property to the value it owns. In other words, the property value is set to the property defined by the custom style (if set), otherwise the property value is set to the default style of the user agent.

Note : initial and unset not supported by IE.

initialis to assign the initial value of the property (initial value) to the element. Initial applies to all CSS properties (the initial value of the property can be found in the property sheet), including the CSS shorthand attribute (global property) all.

inheritThe value is the most interesting-it allows us to explicitly allow an element to inherit a property value from its parent class.

Let's look at an example. First, there is the following paragraph of HTML:

<ul>  <li>Default<ahref="#">Link</a>Color</li>  <liclass="Inherit">Inherit the<ahref="#">Link</a>Color</li>  <liclass="initial">Reset the<ahref="#">Link</a>Color</li>  <liclass="unset">Unset the<ahref="#">Link</a>Color</li></ul>

Now add a style to it with CSS:

{  color:green;}.inherit{  color:inherit;}.initial{  color: initial}.unset{  color: unset;}

Result:

Let's explain what's going on here:

    • The first thing we set <body> color is green.
    • Because color attributes are naturally inherited, all body child elements will have the same green. It is important to note that by default the browser settings link color is blue instead of naturally inheriting the color property, so the first link in our list is blue.
    • The second rule sets a inherit link within the element of a class and inherits its color from the parent class. In this case, it means that the link inherits the color of the parent element, and <li> by default <li> the color comes from its parent element, and <ul> finally inherits from the <ul> <body> element, and <body> is color set to green according to the first rule.
    • The third rule selects any link on the element that uses the class initial and then sets their color to initial . Typically, initial the value is set to black by the browser, so the link is set to black.
    • The last rule selects all the links on the element that use the class unset and then sets their color to unset --that is, we do not set the value. Because the color property is a naturally inherited property, it is actually like setting the value to the inherit same. As a result, the link is set to the same color as body-green.
Reset All property values

CSS Sketch Properties all can be applied to each inherited property, and all inherited properties are applied at once. The value here can be any one of the inherited attributes ( inherit ,,, initial unset or revert ). This is a very handy way to undo the modification of a style. You can then return to a known start point before starting a new modification.

Full text summary from MDN Web Developer site
End
2018-5-31 Thursday

CSS Learning Summary-cascading and inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.