Home > Web Front-end > HTML Tutorial > 【自学CSS碰到的“坑”】谁才是first-child_html/css_WEB-ITnose

【自学CSS碰到的“坑”】谁才是first-child_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:36:36
Original
828 people have browsed it

看过CSS伪类选择器之后,心想也就如此嘛,:first-child选择元素的第一个子元素,有什么难的,可一到实践中,还是到处碰壁啊。

 1 <body> 2     <ul class="fruit"> 3         <li>Apple</li> 4         <li>Orange</li> 5         <li>Pear</li> 6         <li>Grape</li> 7     </ul> 8     <div class="content"> 9         <p>I am learning CSS.</p>10         <p>I want to be a programmer.</p>11     </div>12 </body>
Copy after login

设置ul的第一个子元素的背景颜色,我想当然地使用了 ul:first-child{backgroud-color:#ccc;},结果发现整个ul元素都被选中了!

再回头看手册“:first-child选择器用于选取属于其父元素的首个子元素的指定选择器”,针对上述代码,也就是说应该设置成这样:

li:first-child{backgroud-color:#ccc;}或者.fruit>:first-child{backgroud-color:#ccc;}

同理,若想选择

的第一个

元素,应该设置:

p:first-child{backgroud-color:#789;}或者.content>:first-child{backgroud-color:#789;}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template