您的位置:首页 > Web前端 > CSS

CSS选择器

2016-01-20 13:35 615 查看
1.ID和类选择器

.specialtext {font-style: italic;}
p.specialtext {color: red} /* class为specialtext的p元素 */
.specialtext.featured {font-size: 100%;} /* class为specialtext和featured的元素*/

#specialtext {}
p#specialtext {} /* 类比上面 */


2.上下文选择器

p, body {font-size: 10px;} /* p和body */
artical p {font-weight: bold;} /* artical p是上下级关系,但可以越级 */
section > h2 {font-style: italic} /* 父子选择,section必须是h2的直接父元素 */
h2 + p {font-variant: small-caps;} /* 紧邻同胞选择器,p必须紧邻同胞h2后面 */
h2 ~ a {color: red;} /* 一般同胞选择器,不必紧邻 */


3.通用选择器

* {color: green;}
p * {color: red;} /* p包含的所有元素 */
section * a {font-size: 1.3em;} /* section的孙元素的a,不管其父元素*/


4.属性选择器

/* 带有title属性的img元素,至于其title值是什么不重要 */
img[title] {border: 2px solid blue;}


5.属性值选择器

/* title属性为red flower的img元素 */
img[title="red flower"] {border: 4px solid green;}


6.伪类

链接伪类

link: 等待用户点击的状态

visited: 点击过的连接状态

hover: 鼠标悬停在连接上的状态

active: 连接正在被点击(按下还未释放)

p:hover {background-color: grey;}


focus伪类

获得焦点的元素

input:focus {border: 1px solid blue;}


target伪类

链接的目标元素

<a href="#more_info">more information</a>
<h2 id="more_info">This is the information you are looking for.</h2>

#more_info:target {background: #eee;} /* h2元素 */


结构化伪类

:first-child和:last-child
e:first-child
:nth-child
e:nth-child(n) /* n是一个数值,也可以是even,odd */


7.伪元素

e::first-letter /* e的首字符 */
e::first-line /* 首行 */
e::before/after /* 在e前面/后面添加内容 */


比如

<p class-"age">25</p>


p.age::before {content: "Age: ";}
p.age::after {content: " years.";}


得到的结果为:

Age:25 years.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: