【问题标题】:Target all but first element with class X, where parent element has another element without class X at the beginning定位除第一个类 X 的元素之外的所有元素,其中父元素在开头有另一个没有类 X 的元素
【发布时间】:2015-05-13 08:43:04
【问题描述】:

我想在下面显示的 HTML 中定位除第一个元素之外的所有具有“icon-flight-close”类的元素。我已经确定我不能这样做,因为 header 元素没有这个类,但它有相同的父元素并且在开头定义。

在第一种情况下,我将标题放在#flights div 的开头,在第二种情况下,我将其放在末尾,然后按照我想要的方式应用样式。

HTML:

<div id="flights"  class="form-group col-sm-12">
    <div id="flights-heading-wrapper">
        <label class="heading-big">Flights</label>
     </div>
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>aaaa</p></div></div>
    </div>
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>bbbbb</p></div></div>
    </div>
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>bbbbb</p></div></div>
    </div>
</div>

<div id="flights"  class="form-group col-sm-12">
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>aaaa</p></div></div>
    </div>
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>bbbbb</p></div></div>
    </div>
    <div class="flight row">
        <div class="hand-cursor icon-flight-close col-sm-12 text-left"><div><p>bbbbb</p></div></div>
    </div>
    <div id="flights-heading-wrapper">
        <label class="heading-big">Flights</label>
    </div>
</div>

CSS:

.flight:not(:first-child) .icon-flight-close{
    color: red;
}

这是它的样子: http://jsfiddle.net/gxz9uke2/2/

【问题讨论】:

    标签: html css twitter-bootstrap css-selectors


    【解决方案1】:

    你可以使用

    .flight ~ .flight .icon-flight-close {
        color: red;
    }
    

    【讨论】:

    • 太棒了!好像它起作用了。请解释一下?我做错了什么,你的代码是如何使它工作的?
    • 我会使用~,以防航班不总是直系兄弟姐妹。
    • @koleS: ~general sibling combinator。在这种情况下,它选择出现在另一个.flight 之后的任何.flight 作为兄弟姐妹(然后是其中具有.icon-flight-close 类的任何元素),无论哪个兄弟姐妹出现在它们之间/之前或之后。所以这允许选择器忽略标签。
    • @Adrift 太棒了。感谢您的解释。还有一个问题:在这种情况下,您将如何定位第一个/最后一个 .flight div 元素?
    • @koleS:不幸的是,CSS 没有一种非常方便的方法来选择特定类的第一个和最后一个元素。我建议阅读this answer 以了解原因。可以使用 jQuery 轻松完成,但是使用 .eq() 之类的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2021-11-19
    • 2011-05-15
    相关资源
    最近更新 更多