2017-01-27 99 views
0

我需要将样式应用于p标签只有如果它是父级下的第一个元素。我试着搜索谷歌和堆栈溢出,但我可能没有输入正确的搜索来获得我所需要的,因为我找不到我需要做的示例。如何将样式应用于父级下的特定元素(仅当它是第一个元素时)?

如果我需要在下面的代码中将文本更改为红色,我可以使用哪些CSS?

<div class="main"> 
    <p>This will be red.</p> 
    <p>This will not be red.</p> 
    <p>This will not be red.</p> 
</div> 

<div class="main"> 
    <h1>Title</h1> 
    <p>This will not be red.</p> 
</div> 

<div class="main"> 
    <img src="" alt=""> 
    <p>This will not be red.</p> 
</div> 

回答

4

:first-child选择器将执行此操作。

.main p:first-child { 
 
    color: red; 
 
}
<div class="main"> 
 
    <p>This will be red.</p> 
 
    <p>This will not be red.</p> 
 
    <p>This will not be red.</p> 
 
</div> 
 

 
<div class="main"> 
 
    <h1>Title</h1> 
 
    <p>This will not be red.</p> 
 
</div> 
 

 
<div class="main"> 
 
    <img src="" alt=""> 
 
    <p>This will not be red.</p> 
 
</div>

0
<div class="main"> 
    <p class = "first">This will be red.</p> 
    <p>This will not be red.</p> 
    <p>This will not be red.</p> 
</div> 

<div class="main"> 
    <h1>Title</h1> 
    <p>This will not be red.</p> 
</div> 

<div class="main"> 
    <img src="" alt=""> 
    <p>This will not be red.</p> 
</div> 

只需添加一个简单的类,然后在你的CSS有.first {color: red; }和您的其他p {color: blue; //or whatever colors}

*可能变得单调乏味,但它真的很简单,只是让类或ID,并将它们添加到你想要更具体的风格的元素。

或者只是做Coker的建议,那也行!

0

它所需要的是CSS的几行acomplish这一点。

.main p:first-child { 

    color: red; 
} 

这是使用您的HTML代码。

https://jsfiddle.net/f8Ljkpt5/

+1

OP的问题_“我需要只有当它的母公司下的第一个元素,将样式应用到AP的标签。” _当你的代码适用于他们的榜样,OP不看向只适用于' .main:first-child' - 只是'.main p:first-child' –

+0

你是对的,谢谢先生。 –

相关问题