2017-02-16 4259 views
0

我想用CSS/SASS在我的标记中设置某个<div>的样式,我对为什么不应用这些规则一无所知。这是我的标记:SASS/CSS:第一个孩子选择器不工作

<div class="row addon-header"> 
    <div class="col-sm-3"> 
    // something here 
    </div> 
    <div class="col-sm-9"> 
     <h2>Title</h2> 
     <h6><em>Slogan</em></h6> 
     <div class="col-xs-1"> 
      // I want to access this 
     </div> 
     <div class="col-xs-1"></div> 
     <div class="col-xs-1"></div> 
     <div class="col-xs-1"></div> 
    </div> 
</div> 

这是我想使用它的SASS:

div.addon-header { 
    color: white; 
    > div.col-sm-9 > div.col-xs-1:first-child { 
     background-color: black; 
     padding-left: 0px !important; 
    } 
} 

如果我在SASS删除:first-child选择,它的工作,但很明显,每不仅仅是第一个,这不是我想要的。

我也试过玩弄与做这样的事情

div.addon-header { 
    color: white; 
    > div.col-sm-9 > div.col-xs-1 { 
     &:first-child { 
      background-color: black; 
      padding-left: 0px !important; 
     } 
    } 
} 

div.addon-header { 
    color: white; 
    > div.col-sm-9 { 
     > div.col-xs-1:first-child { 
      background-color: black; 
      padding-left: 0px !important; 
     } 
    } 
} 

或使用:nth-child(1)代替。什么都没有我无能为力。在我的SASS的其他地方,我有以下几点:

.tab-content { 
    >.tab-pane:first-child > form > div.row > div { 
     // rules here 
     > div.picture-container { 
      // rules here 
     } 
    } 
    >.tab-pane { 
     // rules here 
    } 
    >.tab-pane:nth-child(4) > form { 
     // rules here 
    } 
} 

哪个工作得很好。所以在第一个例子中,我真的不明白我做错了什么。任何人都可以帮忙?

+0

这是由于'first-child'选择器的作用方式,'div'不是'h2'的'first-child'。 https://jsfiddle.net/qb2d66d4/1/ –

+0

感谢@arturmoroz和其他人,我想出了它! –

回答

0

col-xs-1需要包装row,因为这个块不是第一个元素。第一个元素是h2

0

您需要:nth-of-type()(或者,在您的情况下为:first-of-type选择器)。

在示例中,您提供的:first-child.col-sm-9元素是h2

div.addon-header { 
    color: white; 
    > div.col-sm-9 > div.col-xs-1:first-of-type { 
     background-color: black; 
     padding-left: 0px !important; 
    } 
} 

注意,虽然,:nth-of-type()选择,如:nth-child()选择,适用于标签而已,不是类名;如果您要在第一个.col-xs-1之前插入另一个div,那么这将不再起作用。

+0

谢谢,我结束了使用@arturmoroz答案,因为在一行中包装cols否定了'padding-left:0px'的需要,所以我保存了一些CSS。但你的答案也适用。 –

相关问题