首页 > 解决方案 > 是否可以有两个带 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>

谢谢!

标签: javascripthtmlcss

解决方案


H2.left_switch引用类名为 的 h2 元素left_switchh2.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 只是一个示例。您不必添加它。


推荐阅读