CSS 特异性

cssweb developmentfront end technology更新于 2025/11/27 5:32:17

特异性使我们能够比较属于同一元素的两个或多个相互冲突的 CSS 规则,并根据浏览器规则确定哪个规则更具体。特异性的顺序如下:−

示例

id selectors(#first) > class selectors(.sample) ,pseudo class(:active) and attribute
selectors([type=”text”]) > type selectors(p, div etc.) and pseudo elements (::after).

以下代码展示了 CSS 中的特异性 −

<!DOCTYPE html>
<html>
<head>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
   width: 200px;
   height: 200px;
   background-color: red;
}
.example {
   width: 150px;
   height: 150px;
   background-color: rgb(47, 0, 255);
}
#test {
   width: 200px;
   height: 200px;
   background-color: rgb(73, 0, 67);
   text-align: center;
   color: white;
   font-size: 20px;
}
</style>
</head>
<body>
<h1>Css specificity example</h1>
<div id="test" class="example">Some text inside div</div>
</body>
</html>

输出

上述代码将产生以下输出 −


相关文章


有用资源