周老师讲:CSS结构选择器

597 阅读3分钟

1. 结构选择器

概念: 结构选择器是对文本结构的一种过滤逻辑,如,是不是第一个,是不是唯一一个等等。

选择器 描述 举例 版本
:first-child 如果它是第一个子元素,就选中 ul>li:first-child{} 2
:last-child 如果它是最后一个子元素,就选中 ul>li:last-child{} 3
:only-child 如果它没有兄弟元素,就选中 li:only-child{} 3
:only-of-type 如果没有同类型的兄弟元素,就选中 li:only-of-type{} 3
:nth-child(n) 选中第N个子元素 ul>li:nth-child(2){} 3
:nth-last-child(n) 选中倒数第N个子元素 ul>li:nth-last-child(2){} 3
:nth-of-type(n) 选中范围内所有该类型中的第N个 ul>li:nth-of-type(2){} 3
:nth-last-of-type(n) 选中范围内所有该类型中的倒数第N个 ul>li:nth-lst-of-type(2){} 3

表格中的N都从1开始的。

2. :first-child / :last-child

概念: 如果它是第一个子元素 / 最后一个子元素,就选中。

布局:

<ul>
    <li><>
    <li><>
    <li><>
    <li><>
</ul>

样式:

/**必须是第一个子元素才行*/
ul li:first-child{ 
	color: red;
}

/**必须是最后一个子元素才行*/
ul li:last-child{ 
	color: green;
}

3. :only-child

概念: 如果它没有兄弟元素,就选中,注意,不考虑类型问题。

布局:

<div>
    <span>1</span>
</div>
<div>
    <span>2</span>
    <span>3</span>
</div>
<div>
    <div>4</div>
    <span>5</span>
</div>
<ul>
    <li>11111<>
</ul>
<ul>
    <li>22222<>
    <li>33333<>
</ul>

样式:

/**我是独生子*/
li:only-child{ 
    color:red;
}

/**我要找到一个span,这个span得是独生子,然后抓到这个span*/
span:only-child{ 
    color:red;
}

4. :only-of-type

概念: 如果没有同类型的兄弟元素,就选中。

布局:

<!--过滤条件:div中有span,并且span类型只有一个-->
<div>
    <span>1</span>
    <div>2</div>
</div>
<div></div>
<ul>
    <li>1<>
    <li>2<>
</ul>

样式:

span:only-of-type{ 
    color:red;
}

div:only-of-type{ 
    color:red;
}

li:only-of-type{ 
    color:green;
}

5. :nth-child(n) / :nth-last-child(n)

概念: 选中第N个 / 倒数第N个子元素。

布局:

<ul>
    <li>1<>
    <li>2<>
    <li>3<>
    <li>4<>
    <li>5<>
    <li>6<>
    <li>7<>
</ul>

样式:

ul > li:nth-child(3){ 
    color:red;
}

ul > li:nth-last-child(3){ 
    color:red;
}

6. :nth-of-type(n) / :nth-last-of-type(n)

概念: 选中范围内所有该类型中的第N个 / 倒数第N个。

布局:

<div>
    <div>1</div>
	<div>2</div>
	<div>3</div>
	<div>4</div>
	<div>5</div>
    
	<span>1</span>
	<span>2</span>
	<span>3</span>
	<span>4</span>
	<span>5</span>

    <p>1</p>
	<p>2</p>
	<p>3</p>
</div>

样式:

div:nth-of-type(3){
    color: red;
}

span:nth-of-type(3){
    color: red;
}

p:nth-last-of-type(3){
    color: red;
}