365bet中文版

CSS样式的继承与覆盖

📅 2025-06-29 06:54:10 👤 admin 👁️ 5872 🏷️ 863

样式的继承

定义:父元素设置了某属性,子元素也会有该属性 下面是会被继承的CSS样式属性:

azimuth, border-collapse, border-spacing,

caption-side, color, cursor, direction, elevation,

empty-cells, font-family, font-size, font-style,

font-variant, font-weight, font, letter-spacing,

line-height, list-style-image, list-style-position,

list-style-type, list-style, orphans, pitch-range,

pitch, quotes, richness, speak-header, speaknumeral,

speak-punctuation, speak, speechrate,

stress, text-align, text-indent, texttransform,

visibility, voice-family, volume, whitespace,

widows, word-spacing

文本相关属性:

font-family, font-size, font-style,

font-variant, font-weight, font, letter-spacing,

line-height, text-align, text-indent, texttransform,word-spacing

列表相关属性:

list-style-image, list-style-position,

list-style-type, list-style

样式的覆盖

规则:

根据引入方式确定优先级 优先级由高到低依次为:“内联属性”——>“写在 style标签里”——>“外部链接”后写的覆盖先写的(同一级别) 即就是在文件上代码行号更靠下的优先级更高加有“!important”的样式,优先级最高 即无论哪一种情况,只要在样式上加了important,那么该样式的优先级最高。加了important的代码如下:

p {

color: white !important;

}

选择器优先级 在选择器不同的情况下,给每种选择器制定一个权值,计算命中一个元素的所有选择器的总权值,值高者获胜

元素选择器: 1 类选择起器: 10 ID选择器: 100 内联选择器: 1000

样式继承与覆盖示例

样式继承不是一个默认行为,实际上而是看某一个属性的默认值是否是inherit。 所谓的浏览器默认样式。a标签的color浏览器默认样式不是inherit。代码如下所示:

.abstract{

color:grey;

}

.abstract a{

color:inherit;

text-decoration:none;

border:thin black solid;

}

.different {

color: red ;

}

.different a{

text-decoration: none ;

border:thin black solid;

}

执行效果如下图:

前面讲到外部文件引用css的优先级比style标签里的低。但是id选择器的优先级是比元素选择器要高的。所以当元素选择器和id选择器都命中同样的元素的时候, id选择器的样式会覆盖元素选择器的样式。 代码如下:

h1{

color:red;

}

#change{

color:blue;

}

执行效果如下:

我们知道内联样式的优先级是最高的,那么当元素已经被内联样式设置的时候。我们通过 !important来覆盖。代码如下:

HelloWord,你看到的是已经经历过三次变换的文字。

h1{

color: red;

}

#change{

color:black !important

}

执行效果如下:

若给一种元素设置了普适的效果,如何通过更精确的选择器将其覆盖掉,代码如下:

a{

color:black;

}

a.hehe{

color:white;

background:grey;

}

当一个元素有两个class的时候,到底哪个class会影响元素呢, 代码如下:

a.hehe1{

color:black;

}

a.hehe2{

color:white;

background:grey;

}

文件上代码行号更靠下的优先级更高,即后写的覆盖先写的。

让span继承abstract的border属性。代码如下:

.abstract{

color:white;

background:grey;

border:medium black solid;

}

span{

border:inherit

}

如上所示,将span 的 border 属性设为“inherit”,span 就会继承父元素的样式。

相关推荐

昔日又帅又强的德系E-50,今日能否称王?

各位车长老爷大家好啊!经过艰苦卓绝的努力,莱茵终于度过了E50的漫长白板期,上手一试,果然比之前的88毫米钓鱼竿手感好了太多(虽然咱

三星手机(Samsung Mobile)的崛起和长期成功是多种因素复杂交织的结果

来源:雪球App,作者: 林文丰,(https://xueqiu.com/3181890538/335870447) 远见卓识与战略转型: 早期对Android的押注: 在智能手机发展初期,三星迅

昔日又帅又强的德系E-50,今日能否称王?

各位车长老爷大家好啊!经过艰苦卓绝的努力,莱茵终于度过了E50的漫长白板期,上手一试,果然比之前的88毫米钓鱼竿手感好了太多(虽然咱