选择第一个不包括div.class的类型

时间:2014-12-29 10:40:40

标签: css

除第一个div为div.error之外,我如何匹配第一个div?

    <div>
            <div class="error">
                <p>Error 1.</p>
                <p>Error 2.</p>
            </div>

            <div> <!--I want to tag this-->
                Content
            </div>
            <div>
                Content
            </div>
            <div>
                Content
            </div>
        </div>

我的尝试:

div > div:first-of-type:not(.error) {color:red}

div > div[class]:not(.error):first-of-type {color:red}

div.error可能出现与否(取决于是否有错误),所以我不能使用像nth-of-type(2)这样的东西

2 个答案:

答案 0 :(得分:3)

您可以使用两个选择器的组合。检查演示以测试两种情况:

&#13;
&#13;
div > div.error:first-of-type + div,
div > div:not(.error):first-of-type {
    color: red;
}
&#13;
<div>
    <div class="error">
        <p>Error 1.</p>
        <p>Error 2.</p>
    </div>
    <div><!-- Should match this-->Content</div>
    <div>Content</div>
    <div>Content</div>
</div>
<hr>
<div>
    <div><!-- Should match this -->Content</div>
    <div>Content</div>
    <div>Content</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

.main div:first-child:not(.error),.main div.error+div{color:red;}
<div class="main">
            <div class="error">
                <p>Error 1.</p>
                <p>Error 2.</p>
            </div>

            <div> <!--I want to tag this-->
                Content :: red
            </div>
            <div>
                Content
            </div>
            <div>
                Content
            </div>
        </div>

<div class="main">
            

            <div> <!--I want to tag this-->
                Content :: red
            </div>
            <div>
                Content
            </div>
            <div>
                Content
            </div>
        </div>