我怎样才能将css选择器复合在一起

时间:2012-03-01 20:43:24

标签: css css3 css-selectors

是否可以使用:not()选择器和:nth-​​of-type(1)选择器?

即。 我想选择第一个没有标题“something”的

<html>
    <head>
        <style type="text/css">
            p
            {
                color:#000000;
            }
            p:not([title=something]):nth-of-type(1)
            {
                color:#ff0000;
            }
        </style>
    </head>
    <body>

        <h1>This is a heading</h1>

        <p title="something">This is a paragraph.</p>
        <p>This is another paragraph.</p>
        <p>This is another paragraph.</p>

        <div>This is some text in a div element.</div>


    </body>
</html>

3 个答案:

答案 0 :(得分:3)

问题是nth-of-type伪类被定义为:

  

[nth-of-type]根据父元素的子元素列表中的位置匹配元素。

因此,伪班:nth-of-type(1)将您的选择限制在p位置的1子女。

您的伪班not([title=something])将您的选择限制为p元素而没有属性/值title='something',就像您怀疑的那样。

两个选择器一起导致没有元素,因为位置p的{​​{1}}子项具有1

为了更好地理解,请尝试以下方法:

title='something'

更多信息:Pseudo-classesnth-of-type

答案 1 :(得分:3)

nth-of-type作用于原始选择器(p),它不会对p:not([title=something])的结果起作用。

p:not([title=something]):nth-of-type(1)

这就是说,找到没有标题的<p>&#34; someting&#34;那个也是页面上的第一个<p>。这并没有找到任何元素,因为第一个<p>有标题&#34;某些&#34;。

你想要的是第一个<p>,它不包含标题&#34;某些东西&#34;。我不知道CSS是否有一个很好的方法。

如果您愿意使用jQuery,可以使用:

$('p:not([title="something"]):eq(0)')

或:

$('p').not('[title="something"]').eq(0)

答案 2 :(得分:2)

正如其他答案所述,:nth-of-type()仅指元素类型,在本例中为p。选择器p:not([type=something]):nth-of-type(1)仅表示p元素:not([type=something]),也是第一个p

无论如何,你要求可以使用普通的兄弟选择器在纯CSS中完成,但可能涉及不必要的冗长和重复的选择器:

p:not([title=something]) ~ p:not([title=something])
{
    color:#000000;
}
p:not([title=something])
{
    color:#ff0000;
}

如果您只想将其应用于没有p属性的title元素,则可以稍微缩短选择器:

p:not([title]) ~ p:not([title])
{
    color:#000000;
}
p:not([title])
{
    color:#ff0000;
}

我想出了这个技术首先用于类,我更详细地描述了here,但是它可以应用于很多东西,包括属性,我有另一个例子{{3 }}