gpt4 book ai didi

html - 如果为元素同时指定了 id 和 class,将应用哪个属性?为什么?

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:59 25 4
gpt4 key购买 nike

我有这个:

<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>My Social Network</title>
</head>
<body>
<div id="best_friend" class="friend" ></div>
<div class="family"></div>
<div class="enemy" id="archnemesis"></div>

</body>
</html>


div {
display: inline-block;
margin-left: 5px;
height: 100px;
width: 100px;
border-radius:100%;
border: 2px solid black;

}

#best_friend {
border: 4px solid #00C957;
}

.friend {
border: 2px dashed #008000;
}

.family {

border: 2px dashed #0000FF;

}

.enemy {
border: 2px dashed #FF0000;

}

#archnemesis {
border: 4px solid #CC0000;
}

我的问题是:请注意我是如何为 classid 定义 border 的。应用的 border 是来自 id 的那个。为什么这样?为什么 id 中的 border 规范覆盖了 class 中的规范。

最佳答案

浏览器根据Specificity确定以什么顺序应用哪些样式,较高的数字决定将应用哪些样式。

通用选择器的特异性为 0,0,0,0。
* = 0

HTML 选择器的特异性为 1。
pdiv 等。= 1 个

因此每个 HTML 选择器都增加了特异性。
div p = 2, div p span = 3

类选择器的特异性为 10。
.class = 10

类选择器与 HTML 选择器相结合。
div p.class = 12

ID 选择器的特异性值为 100。
#id = 100

ID 选择器与 HTML 选择器相结合。
#id div = 101

!important 覆盖所有其他样式,除非与另一个选择器结合使用。table td {height: 50px !important;} 将覆盖仅应用于 table 中的 td 的任何 height 样式>.

内联样式具有最高的特异性 1000。
style= = 1000

有用的资源

CSS Specificity: Things You Should Know
Specificity | HTML Dog

关于html - 如果为元素同时指定了 id 和 class,将应用哪个属性?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com