我想将类为 ind、id 为 3 的 div 元素的 div 标签的背景颜色更改为蓝色。 这是我的 CSS
h1 {
text-align: center;
}
#identify {
text-align: center;
}
.container {
border-style: dotted;
width: 800px;
height: 400px;
position: absolute;
right: 550px;
}
.ind {
float: left;
position: relative;
top: 40%;
padding: 50px;
left: 200px;
}
.ident {
position: relative;
display: inline;
float: left;
text-align: center;
padding: 10px;
}
#2.ind {
background-color: blue;
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="project" content="hello">
<title></title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="2css.css">
<h1>Set the distance!</h1>
<p id="identify">To play this game, you must be at least 18 years old. You must also fill out some information.</p>
<div class="container">
<div class="ind" id="2">2</div>
<div class="ind" id="3">3</div>
<div class="ind" id="4">4</div>
</div>
</body>
</html>
在浏览器中,由于某些原因,id 为 2 的 div 类 ind 的背景颜色不会更改为蓝色。有什么建议吗?
最佳答案
尽管有许多不同的说法,HTML5 中的 ID 确实可以以数字开头。但是,在其他情况下提及这些元素时必须小心。首先是一些代码:
console.log(document.querySelector('#\\0032') == null);
#\0032 { background-color: black; color: white }
[id="2"] { background-color: white; color: black }
<p id="2">
Two
</p>
您确实需要使用 Unicode 转义序列对数字进行转义(我已将其扩展为四位十六进制表示,这样就清楚了)。您可以使用属性选择器,但这会更改其 specificity (see this question's answers for more information on that topic)低于 ID。您可以看到第二个选择器不够具体,无法覆盖 ID 选择器。不一定是坏事,但肯定是需要注意的事情。
请注意,尽管它可以工作,并且被相关规范所允许,但由于需要在 CSS 中进行转义,因此通常不被接受。请注意,这也意味着在 DOM 方法 querySelector
中,当在 JavaScript 中访问时,转义字符也必须转义(因为您必须使用 JavaScript 字符串,它使用相同的转义字符)。我也在代码片段中添加了一个例子。
关于html - 如何更改 div 标签内的 div 标签集的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54559359/