选择器:通过选择器可以选中页面中的一组元素,然后为其设置样式
1.元素选择器
根据标签名,选中页面中的指定元素 语法:标签名{ }
例子:div{} p{} h1{}
2.id选择器
根据元素的id属性值选中一个唯一的元素 语法:#id {}
例子:#box1{}
3.id选择器
根据元素的class属性值选中一组元素 语法:.id {}
例子:.box1{}
4.通配选择器
选中页面中的所有元素 语法:*{}
通配选择器的性能比较差,尽量避免使用
5复合选择器
a.逗号:并列 div,span
b.空格:后代 #list li
c.大于号:子元素选择器 语法:父元素 > 子元素 {}
代码:
<!DOCTYPE HTML> <html> <head> <style type="text/css"> h1 > strong {color:red;} </style> </head> <body> <h1>This is <strong>very</strong> <strong>very</strong> important.</h1> <h1>This is <em>really <strong>very</strong></em> important.</h1> </body> </html>
效果:
d.加号:兄弟元素选择器 选取后一个兄弟元素 前一个 + 后一个
代码:
<!DOCTYPE HTML> <html> <head> <style type="text/css"> h1 + p {margin-top:50px;} </style> </head> <body> <h1>This is a heading.</h1> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> </body> </html>
效果:
e.~ :选取后边所有的兄弟元素 前一个 ~ 后边所有
代码:
<!DOCTYPE html>
<html>
<head>
<style>
p~ul
{
background:#ff0000;
}
</style>
</head>
<body>
<div>一个 div 元素。</div>
<ul>
<li>咖啡</li>
<li>牛奶</li>
<li>茶</li>
</ul>
<p>第一段。</p>
<ul>
<li>咖啡</li>
<li>牛奶</li>
<li>茶</li>
</ul>
<h2>另一个列表</h2>
<ul>
<li>咖啡</li>
<li>牛奶</li>
<li>茶</li>
</ul>
</body>
</html>
效果:
6.属性选择器
根据元素的属性选择指定元素
a.[attribute] 用于选取带有指定属性的元素。
代码:
<html> <head> <style type="text/css"> [title] { color:red; } </style> </head> <body> <h1>可以应用样式:</h1> <h2 title="Hello world">Hello world</h2> <a title="W3School" href="http://w3school.com.cn">W3School</a> <hr /> <h1>无法应用样式:</h1> <h2>Hello world</h2> <a href="http://w3school.com.cn">W3School</a> </body> </html>
效果:
b.[attribute=value]用于选取带有指定属性和值的元素。
c.[attribute~=value]用于选取属性值中包含指定词汇的元素。
代码:
<!DOCTYPE html> <html> <head> <style> [title~=flower] { border:5px solid yellow; } </style> </head> <body> <p>title 属性中包含单词 "flower" 的图片会获得黄色边框。</p> <img src="../img/1111.jpg" title="tulip flower" /> <br /> <img src="../img/2222.jpg"" title=" lupuflower" /> <p><b>注释:</b>对于 IE8 及更早版本的浏览器中的 [attribute~=value],必须声明 <!DOCTYPE>。</p> </body> </html>
效果:
d.[attribute|=value]用于选取带有以指定值开头的属性值的元素,该值必须是整个单词。(适用于所有标签)
代码:
<!DOCTYPE html> <html> <head> <style> [lang|=en] { background:yellow; } </style> </head> <body> <p lang="en">Hello!</p> <p lang="en-us">Hi!</p> <p lang="en-gb">Ello!</p> <p lang="us">Hi!</p> <p lang="zh">nihao!</p> <p><b>注释:</b>对于 IE8 及更早版本的浏览器中的 [attribute|=value],必须声明 <!DOCTYPE>。</p> </body> </html>
效果:
e.[attribute^=value]匹配属性值以指定值开头的每个元素
f.[attribute$=value]匹配属性值以指定值结尾的每个元素。
g.[attribute*=value]匹配属性值中包含指定值的每个元素。
注意: [属性名~="属性值"] [属性名|="属性值"] [属性名^="属性值"] 区别
testa,test a,test-a
*=te:属性值包含te的就行
~=te:属性值包含te的 并且 带空格的,其余两个不能选中(带空格的专用)
^=te:属性值以te开头的就行
|=te:属性值以te开头的 并且 带 '-' 的,其余两个不能选中(带'-'的专用) 属性值只要全等就都能选中。不管有没有空格或 '-' 。