请看下面的html代码:
<div class="container">
<div class="sidebar-column">
<h2 class="title">Column 01</h2>
<p>content01</p>
<p>content02</p>
<p>content03</p>
</div>
<div class="sidebar-column">
<h2 class="title">Column 02</h2>
<p>content04</p>
<p>content05</p>
<p>content06</p>
</div>
</div>
我只想选择内容为“Column 02”的第二个标题,是否仅使用 CSS 就可以做到这一点?
我尝试了很多方法,包括选择第二个子类“sidebar-column”的标题“h2”,但不起作用:
<style>
div.sidebar-column:nth-child(2) > h2.title {
background-color: red;
}
</style>
添加样式“background-color: red”后,第二个“h2”应该将背景颜色更改为红色,但没有任何反应。
和想法?谢谢!
编辑:我已经找到解决问题的方法。只需删除“>”。 CSS 现在变成:
<style>
div.sidebar-column:nth-child(2) h2.title {
background-color: red;
}
</style>
现在它在 Wordpress 添加 CSS 中工作。但我仍然不知道为什么。
最佳答案
有两种方法。
解决方案 1- 再创建一个 css 类 (eg-class2) 并将这两个类都添加到第二个 h2 元素。
<div class="container">
<div class="sidebar-column">
<h2 class="title">Column 01</h2>
<p>content01</p>
<p>content02</p>
<p>content03</p>
</div>
<div class="sidebar-column">
<h2 class="title class2">Column 02</h2>
<p>content04</p>
<p>content05</p>
<p>content06</p>
</div>
</div>
第二个类将包含代码-
<style>
.class2{
background-color: red;
}
</style>
解决方案 2- 或者,如果您只想将红色背景色添加到 Column 02
,您可以编写内联 CSS 代码
<div class="container">
<div class="sidebar-column">
<h2 class="title">Column 01</h2>
<p>content01</p>
<p>content02</p>
<p>content03</p>
</div>
<div class="sidebar-column">
<h2 class="title" style="background-color:red;">Column 02</h2>
<p>content04</p>
<p>content05</p>
<p>content06</p>
</div>
</div>
关于html - CSS - 在具有相同标签名称和属性的其他元素中选择特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485213/