您的位置:首页 > Web前端 > CSS

css样式优先级

2018-03-24 23:46 417 查看
有时在设置 HTML 元素时,会遇到相互冲突的多个样式。这时,到底是选择哪个的样式呢?看完下面的文章,你就懂了

1.在body上设置样式,

<style type="text/css">
body {
color: red;
}
</style>


<h1>Hello World!</h1>


运行结果:



如图,会采取body的样式

2.给h1加个class类

<style type="text/css">
body {
color: red;
}
.green-text {
color: green;
}
</style>


<h1 class="green-text">Hello World!</h1>


运行结果:



如图,class覆盖了body的样式,字体变成了绿色,所以class的优先级大于body

3.给h1再加一个class类

<style type="text/css">
body {
color: red;
}
.green-text {
color: green;
}
.blue-text {
color: blue;
}
</style>


<h1 class="green-text blue-text">Hello World!</h1>


运行结果:



如图,字体变成了新定义的蓝色字体

此处需要注意的是:在 HTML 中这些 class 如何排序是无所谓的。

但是!在

<style type="text/css">
body {
color: red;
}
.green-text {
color: green;
}
.blue-text {
color: blue;
}
#pink-text {
color: pink;
}
</style>


<h1 class="green-text blue-text" id="pink-text">Hello World!</h1>


运行结果:



如图,字体点成了粉色

此处注意:你声明的 CSS 类选择器在上面还是下面是无所谓的,因为 id 属性总是具有更高的优先级,会覆盖它们

得到:id的优先级大于class

5.给h1加一个行内样式

<style type="text/css">
body {
color: red;
}
.green-text {
color: green;
}
.blue-text {
color: blue;
}
#pink-text {
color: pink;
}
</style>


<h1 class="green-text blue-text" id="pink-text" style="color: black">Hello World!</h1>


运行结果:



如图,字体变成了黑色,

得到:行内样式的优先级高于id

别急,还没完,还有个最强大的

6.!important

在元素的 color 声明加上关键字 !important,就能 100% 确保你的 h1 颜色是这个元素申明的颜色。

如,我们想让前面的蓝色显示出来,则只需改

.blue-text {
color: blue !important;
}


运行的效果就会变成蓝色字体了

所以,最终得出的结论是,1-6 优先级逐步提高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css样式优先级