本周学习CSS的选择器。
工作中最常使用的就是元素选择器,ID选择器,类选择器,后代选择器。
还有一些并不常用但是功能强大的选择器容易被忽视,这次学习总结下。
1.后代选择器和子代选择器
后代选择器:element1 element2, 查找是element1后代的所有element2
???<style type="text/css"> ???????.myapp p { ???????????????background: green; ????????} ????</style> ???<div class="wrapper"> ???????<div class="myapp"> ???????????<p>通过子代选择器改变样式</p> ???????????<div> ???????????????<p>通过后代选择器改变样式1</p> ???????????????<p>通过后代选择器改变样式2</p> ???????????</div> ???????</div> ???</div>
子代选择器:element1>element2, 查找是element1子代的element2
???<style type="text/css"> ???????.myapp>p { ???????????background: red; ???????} ???</style> ???<div class="wrapper"> ???????<div class="myapp"> ???????????<p>通过子代选择器改变样式</p> ???????????<div> ???????????????<p>通过子代选择器不能改变样式1</p> ???????????????<p>通过子代选择器不能改变样式2</p> ???????????</div> ???????</div> ???</div>
2.伪类选择器:first-child和:first-of-tye
first-child:element:first-child,查找element,该element是其父的第一个子元素
???<!-- 第一个和第三个p的背景色能变红,span的背景色不能变红 --> ???<style type="text/css"> ???????p:first-child { ???????????background: red; ???????} ???????span:first-child { ???????????background: red; ???????} ???</style> ???<div class="wrapper"> ???????<div class="myapp"> ???????????<p>这是第一个p元素,也是第一个div的第一个子元素</p> ???????????<span>这是第一个span元素</span> ???????????<span>这是第二个span元素</span> ???????????<p>这是第二个p元素</span> ???????????<div> ???????????????<p>这是第三个p元素,也是第二个div的第一个子元素</p> ???????????????<p>这是第四个p元素</p> ???????????</div> ???????</div> ???</div>
first-of-tye:element:first-of-tye,查找element,该element是其父的第一个该类型子元素
???<!-- 第一个第三个p和第一个span的背景色都能变红 --> ???<style type="text/css"> ???????p:first-of-type { ???????????background: red; ???????} ???????span:first-of-type { ???????????background: red; ???????} ???</style> ???<div class="wrapper"> ???????<div class="myapp"> ???????????<p>这是第一个p元素,也是第一个div的第一个子元素</p> ???????????<span>这是第一个span元素</span> ???????????<span>这是第二个span元素</span> ???????????<p>这是第二个p元素</span> ???????????<div> ???????????????<p>这是第三个p元素,也是第二个div的第一个子元素</p> ???????????????<p>这是第四个p元素</p> ???????????</div> ???????</div> ???</div>
3.伪类选择器:last-child和:last-of-tye
和2正好相反
4.伪类选择器:nth-child(n)和:nth-of-type(n)
2的升级版,更加灵活
nth-child(n):element:nth-child(n),查找element,该element是其父的第n个子元素
nth-of-type(n):element:nth-of-type(n),查找element,该element是其父的第n个该类型子元素
5.伪类选择器:nth-last-child(n)和:nth-last-of-type(n)
3的升级版
前端之CSS——CSS选择器
原文地址:https://www.cnblogs.com/chechedan/p/9005113.html