For example, the tag P may have related attribute values set multiple times in embedded style sheets and external style sheets (such as color: red;/color: blue). So which value does the browser use to display the style of P? ? ? This is how CSS works. (The degree of specificity is more important)
CSS has three working mechanisms: 1. Inheritance 2. Cascading 3. Specification (The cascading principle is based on inheritance and specificity)
1. Inheritance: Ancestor elements in CSS will pass one thing to descendants: the value of a CSS property. Body is the ancestor of all elements. If we specify body{color:red;}, then all elements in the document inherit this style. This is why, after we write a line of text in the Notepad program, we rename it to: xxx.html. When opened in different browsers, there will be different font effects, because each browser has its own predefined style. table, which includes the font attribute in the body, and when we open our Html with a browser, we inherit this attribute.
Of course, not all attributes can be inherited. Most of the attributes that can be inherited are related to text, such as color, font, font size, etc. Some attributes are meaningless if inherited, or will affect the layout of the page if inherited, such as those involving element positioning, margin, padding, border and other attributes.
2. Cascading: This is the C (cascading) in CSS, which is mainly based on the style source and specificity.
a) Style source: The following is the order in which the browser cascades styles from each source:
is yellow
例子3:选择特指度高的(如按顺序,应该选择link的黄色,但是style中的特指度高 1-0-2 大于 1-0-1,所以选特指度高的红色),后面读取的特指度低的就不会覆盖前面特指度高的。<style> body div #li1{color: red;}</style><link rel="stylesheet" href="demo.css"></head><body> <div id="div1"> <ul class="ul1"> <li id="li1" class="li1">列表项1</li>
demo.css
div #li1{
color:yellow;}
为红色
例子4:行内style有最高优先级,前面的代码不变,只在p中加了style blue,列表项立马变成蓝色虽然行内的有最高优先级,但是行内style本身就不常用(不方便移植,增加网页大小)<li id="li1" class="li1" style="color:blue;">列表项1</li>
例子5 :设定的样式优于继承的样式,即使继承的样式特指度高(在li中加入em,em继承了li的特指度是102,em本身的特指度是001,但是仍然选em)<style> body div #li1{color: red;} em{ color:black;}</style></head><body> <div id="div1"> <ul class="ul1"> <li id="li1" class="li1"><em>列表项1</em></li> </ul>列表项为黑色。