续CSS学习笔记(一)。
4.2高级选择器(现查现用)
4.2.1层次选择器
先设计网页框架。

后代选择器:在某个元素的后面 祖父 父亲 儿子 孙子
1 2 3
| body p{ background: #24c497; }
|
子选择器:只有一代,儿子
1 2 3 4
| body>p{ background: #f39cff; }
|
相邻兄弟选择器:同辈
”弟弟“选择器
只有一个相邻兄弟,向下
1 2 3 4 5 6
| .active+p{ background: #f39cff; } <p class="active">p1</p> <p>p2</p>
|
通用”弟弟“选择器
当前选中元素向下的所有兄弟元素
1 2 3 4
| .active~p{ background: #f39cff; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> /*兄弟选择器 只有一个,向下 */ .active~p{ background: #f39cff; } </style> </head> <body> <p class="active">p1</p> <p>p2</p> <p>p3</p> <ul> <li> <p>p4</p> </li> <li> <p>p5</p> </li> <li> <p>p6</p> </li> </ul> <p>p7</p> <p>p8</p> </body> </html>
|
4.2.2结构伪类选择器
我们直接从例子上手:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>结构伪类选择器</title>
<!--避免使用class和id选择器--> <style> ul li{ height: 30px; list-style: none; text-indent: 2em; } ul li:first-child{ background: #f39cff; } ul li:last-child{ background: #24c497; }
p:nth-child(1){ background: darkorange; }
p:nth-of-type(2){ background:firebrick; } </style> </head> <body> <h1>h1</h1> <p>p1</p> <p>p2</p> <p>p3</p> <ul> <li>li1</li> <li>li2</li> <li>li3</li> </ul> </body> </html>
|

再把h1注释掉,试试:

4.2.3属性选择器(常用)
把id和class选择器结合使用。
使用语法
1.属性名
2.属性名=属性值 =是绝对等于,*=是包含这个元素,^=以这个开头,$=以这个结尾
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>结构伪类选择器</title> <style> .demo a{ /* 作为演示,不需要记住 */ float:left; display: block; height: 50px; width: 50px; border-radius: 10px; background: darkorange; text-align: center; text-decoration: none; margin: 5px; font: bold 20px/50px Arial; } /*选择存在id属性的元素,正则表达式 1.属性名 2.属性名=属性值 =是绝对等于,*=是包含这个元素,^=以这个开头,$=以这个结尾 */ a[id=first]{ background: #f39cff; } a[class *= last]{ background: #24c497; } a[href ^= images]{ background: yellow; } </style>
</head> <body> <p class="demo">
<a href="http://www.baidu.com" class="links item first" id="first">1</a> <a href="" class="links item first" target="_blank" title="test">2</a> <a href="images/123.html">3</a> <a href="images/12.pdf">4</a> <a href="../images/1.txt" class="links item last">5</a> </p> </body> </html>
|