CSS可以有两个h2吗?



我只是在练习一些html/css/js,并考虑创建一个小程序,就像一个打开和关闭图像的电灯开关。 一切都很好,除了我的"ON"按钮和"OFF"按钮具有相同的标题"H2",所以当我进入 CSS 时,它不知道哪个是可以理解的。我尝试将"H2"分别重命名为"H2.left_switch"和"H2.right_switch"<- 在某处看到它,但它不起作用/它没有显示正确的标题。

.HTML

h1 {
position: absolute;
left: 65px;
top: 150px;
}
h2 {
position: absolute;
left: 40px;
top: 150px;
}
h2 {
position: absolute;
left: 100px;
top: 150px;
}
.leftButton {
position: absolute;
top: 300px;
left: 60px;
width: 40px;
height: 30px;
background-color: gray; 
}
.rightButton {
position: absolute;
top: 300px;
left: 130px;
width: 40px;
height: 30px;
background-color: gray; 
}
.backBoard {
position: absolute;
top: 210px;
left: 40px;
width: 150px;
height: 150px;
background-color: rgb(218, 216, 216); 
}
<!DOCTYPE html>
<html>
<link rel = "stylesheet" type = "text/css" href = "gayle.css">
<head>
<h1>FESTA</h1>
<h2> ON </h2>
<h2> OFF </h2>
</head>
<body>
<div class="center">
<div class="backBoard"></div>
<!--on-->
<div class="leftButton"></div>
<!--off-->
<div class="rightButton"></div>
<img id = "btsArmyBomb" src = "btsArmyBomb.png"/>
</body>
</html>

谢谢!

>H2.left_switch是指类名为left_switch的 h2 元素。h2.right_switch元素也是如此。

只需在 h2 元素中添加一个类名,如下所示:

<h1>FESTA</h1>
<h2 class="left_switch"> ON </h2>
<h2 class="right_switch"> OFF </h2>

然后像这样定位 CSS 中的 h2 元素:

h2 {
exampleStyle: exampleProperty; /* This would apply to both h2 */
}
h2.left_switch { /* This would apply to the h2 with ON */
position: absolute;
left: 40px;
top: 150px;
}
h2.right_switch { /* This would apply to the h2 with OFF */
position: absolute;
left: 100px;
top: 150px;
}

:注:css 中的第一个 h2 只是一个示例。您不必添加它。

<h2 class="on"> ON </h2>
<h2 class="off> OFF </h2>
.on{
position: absolute;
left: 40px;
top: 150px;
}
.off{
position: absolute;
left: 100px;
top: 150px;
}

最新更新