css first-child实例及详解

WBOY
Release: 2016-06-01 09:53:26
Original
1700 people have browsed it
<code class="language-html">
    <ul class="fruit">
        <li>Apple</li>
        <li>Orange</li>
        <li>Pear</li>
        <li>Grape</li>
    </ul>
    <div class="content">
        <p>I am learning CSS.</p>
        <p>I want to be a programmer.</p>
    </div>
</code>
Copy after login

如何设置ul的第一个子元素的背景颜色?我想很多人会想当然的这样使用

<code class="language-css">ul:first-child{backgroud-color:#ccc;}</code>
Copy after login

结果整个ul元素都被选中了!这样是错误的。

 

我们可以看看手册,first-child选择器用于选取属于其父元素的首个子元素的指定选择器”,这里要理解其父元素。针对上述代码,也就是说应该设置成这样:

<code class="language-css">li:first-child{backgroud-color:#ccc;}</code>
Copy after login

或者

<code class="language-css">.fruit>:first-child{backgroud-color:#ccc;}</code>
Copy after login

Related labels:
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