摘要:Share interest, spread happiness, increase knowledge, and leave beautiful.
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来
“学越千山:CSS技巧——CSS继承”
欢迎您的访问。
Share interest, spread happiness, increase knowledge, and leave beautiful.
Dear, this is the LearingYard Academy!
Today, the editor brings the
Learning over a thousand mountains:CSS Techniques—CSS inherited,
Welcome to visit!
思维导图
1. 给 HTML 的 body 元素添加样式
1.Adding Styles to the HTML body Element
当您为body 元素设置样式时,某些属性(如 color 和 font-family)会被子元素继承,而某些属性(如background-color)不会自动继承。
When you apply styles to the body element, certain properties (such as color and font-family) are inherited by child elements, while others (such as background-color) are not automatically inherited.
解释(Explanation):
background-color不会被子元素继承,因此 h1 和 p 的背景仍是透明的。
The background-color property is not inherited by child elements, so the backgrounds of h1 and p remain transparent.
color和 font-family 会被子元素继承,因此 h1和 p 的文本颜色为绿色,字体为等宽字体。
The color and font-family properties are inherited by child elements, so the text color of h1 and p is green, and the font is monospace.
2. 样式中的优先级
2. Specificity in Styles
CSS 的优先级决定了当多个规则作用于同一个元素时,哪个规则会生效。优先级从低到高依次为:
CSS specificity determines which rule takes precedence when multiple rules apply to the same element. The order of specificity from lowest to highest is as follows:
继承样式
Inherited Styles
继承的样式没有优先级,只有当没有其他规则显式定义时,继承的样式才会生效。
Inherited styles have no specificity and only take effect when no other rule explicitly defines the property.
元素选择器(标签选择器)
Element Selectors (Tag Selectors)
例如h1, p, div 等。
For example, h1, p, div, etc.
类选择器
Class Selectors
例如.my-class。
For example, .my-class.
优先级高于元素选择器
Has higher specificity than element selectors.
ID 选择器
ID Selectors
例如#my-id。
For example, #my-id.
优先级高于类选择器
例如。
Has higher specificity than ID selectors.
!important
!important:
使用!important 可以强制提升某个规则的优先级,覆盖所有其他规则(除非另一条规则也使用了 !important 且优先级更高)。
Using !important can forcibly elevate the specificity of a rule, overriding all other rules (unless another rule also uses !important with higher specificity).
解释(Explanation):第一个
元素使用元素选择器 p,颜色为蓝色。The first element uses the element selector p, and its color is blue.第二个
元素使用了类选择器 .highlight,颜色为橙色。The second element uses the class selector .highlight, and its color is orange.第三个
元素使用了 ID 选择器 #special,颜色为紫色。The thire element uses the ID selector #special, and its color is purple.第四个
元素:使用了内联样式 style="color: red;",但被类选择器中的!important 覆盖,因此最终颜色为绿色。The fourth element:Uses the inline style style="color: red;", but it is overridden by the !important rule in the class selector, so the final color is green.
今天的分享就到这里了,
如果您对文章有独特的想法,
欢迎给我们留言。
让我们相约明天,
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:百度百科,CSDN
本文由LearningYard新学苑整理并发出,如有侵权请后台留言沟通。
来源:小李论科技