CSS-在其他具有相同标签名称和属性的元素中选择特定元素

时间:2018-07-23 18:34:13

标签: html css css3

请参见以下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>

我只想选择内容为“第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中使用。但是我仍然不知道为什么。

2 个答案:

答案 0 :(得分:0)

有两种方法。

解决方案1-再增加一个CSS类(例如,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>

答案 1 :(得分:-1)

最好的方法是将数据属性添加到模板中,然后在CSS中使用该数据属性进行选择。 工作http://jsfiddle.net/Ls8EP/65/ link