针对第一个不包含某些内容的div

时间:2016-05-04 12:39:27

标签: html css

我有一个页面,其中包含几个类名为row的div。

<section>
    <div class="row"> [...] </div>
    <div class="row"> [...] </div>
    <div class="row"> [...] </div>
</section>

我想定位其中的第一个,以便我可以对它们应用一定的间距。

section div:nth-of-type(1) {
    margin-top: 10px;
}

但是,在某些情况下,我想要影响的div实际上并不是该部分中的第一个div。它是包含noscript标记的div之后的第一个div。

在这种情况下,如何确保我定位正确的div?还有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

使用CSS无法根据子元素选择元素(不管是否存在)。

使用jQuery,您可以尝试类似:

$('div.row:not(:has(noscript))').css('margin-top', '10px');

答案 1 :(得分:0)

如果您使用nth-of-typefirst-of-type,则此类型表示<div><p>等。如果您使用类选择器,它将无效,因为类型保持不变。

例如

<p>hello</p>
<div class="row">hello</div>

在上面的代码中,如果您使用div:nth-of-type(1),那么它将捕获<div class="row">hello</div>因为它的第一个div。

示例:https://jsfiddle.net/czv0z93t/

<强>但是

<div class="first">Hello</div>
<div class="row">Hello</div>

在上面的代码中,如果你使用.row:nth-of-type(1)它将无效,因为它的前一个元素类型也是div。

所以在这里你可以简单地使用.row:nth-child(2)

示例:https://jsfiddle.net/czv0z93t/1/

答案 2 :(得分:0)

我会有一个更轻松的生活,并为所有想要具有特殊样式的人分配一个课程,如<div class='row no-top-border'>

虽然你绝对可以试验div.row > div[noscript], div.row:first-child {}

相关问题