:第一个子选择器不起作用

时间:2014-01-16 08:44:34

标签: html css css-selectors

我想为第一个<article class="type-reviews">元素提供更多宽度,所以我尝试过:

/*this is what I had previously and works right*/
#show-reviews .type-reviews {
    display: inline-block; 
    width: 31%;  
    margin-right: 2% !important;
    padding: 0px; 
    vertical-align: text-top;
}

新规则:

/*this is what I've added to change the first element width*/
#show-reviews .type-reviews:first-child {
    width: 50% !important;  
}

但是新的CSS不会改变任何东西。即使使用Firebug进行检查,似乎该规则也未应用于第一个元素。

HTML是下一个:

...
<div id="show-reviews">
    <div id="banner-lateral">...</div>
    <article id="post-300" class="post-300 type-reviews status-publish hentry has-post-thumbnail">...</article>
    <article id="post-222" class="post-222 type-reviews status-publish hentry has-post-thumbnail">...</article>
    ...
</div>

4 个答案:

答案 0 :(得分:2)

这是因为您的.type-reviews 不是第一个孩子,您的div元素是。这是第一个article元素,因此您可以使用:first-of-type

#show-reviews .type-reviews:first-of-type {
    width: 50%;  
}

此外,你真的不需要在这里使用!important,因为你的新选择器具有比旧选择器更高的特异性。

供参考:

<div id="show-reviews">
    <div ...>...</div>            <!-- First child, first of type (div) -->
    <article ...>...</article>    <!-- Second child, first of type (article) -->
    ...
</div>

答案 1 :(得分:1)

没有看到html我无法确定,但我猜可能有一个不同的元素是容器中的第一个子元素,如下所示:

<div id="show-reviews">
    <span>some other element</span>
    <div class="type-reviews">This is not the first child</div>
    <div class="type-reviews">This is another..</div>
</div>

要么确保在您想要的元素之前没有其他元素,要么考虑使用:first-of-type选择器。

答案 2 :(得分:1)

FROM http://www.w3schools.com/cssref/sel_first-of-type.asp

  

:first-of-type选择器匹配第一个元素   特定类型的孩子,其父母。

     

这与:nth-​​of-type(1)相同。

CSS选择器模块3中引入了

:first-of-type,这意味着旧版本的浏览器不支持它。但是,现代浏览器支持无可挑剔,新的伪选择器广泛用于生产环境

来自CSS3 selector :first-of-type with class name?

  

不,:first-of-type伪类选择其第一个元素   type(div,p等)。使用类选择器(或类型选择器)   伪类意味着如果元素具有给定的类,则选择它   (或属于给定类型)并且是其中的第一个类型   兄弟姐妹。

     

不幸的是,CSS没有提供:第一类选择器   只选择第一次出现的类。作为一种解决方法,你可以   使用这样的东西:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
  [1]: http://www.w3schools.com/cssref/sel_first-of-type.asp.

所以你必须使用

#show-reviews .type-reviews ~ .type-reviews{
     width: 50%;
}

答案 3 :(得分:0)

我认为它应该适用于chrome和Firefox两者。可能有可能CSS的其他部分覆盖你的规则

相关问题