规则结构
选择器 {申明块}
h1 {color:red;background:yellow;}
元素选择器
选择器分组
h1,h2,h3 {color:silver}
申明分组
h1 {color:blue;background:silver;}
类选择器
选择器为"."+className
.warning{font-weight:bold;}/*所有包含warning class都会rend*/
p.warning{font-weight:bold;}/*所有包含warning class 的p 元素都会rend*/
多类选择器:把类选择器链接到一起,同时包含这些类名的元素可以被render。
.warning{font-weight: bold;}
.urgent{font-style: italic;}
.warning.urgent{background: silver}/*多类选择器*/】
p.warning.urgent{background: silver}/*多类选择器 仅选择包含两种class的P元素*/
ID选择器
ID选择器前面有一个“#”号作为标识。
#lead-para{font-weight: bold}
属性选择器
选择具有某种属性的元素进行渲染。选择器由 元素标识+[属性名称] 组合而成。
planet[moons]{font-weight: bold;}/*所有具有moons属性的planet元素字体加粗*/
*[title]{font-weight: bold}/*所有具有title属性的元素字体加粗*/
a[href][title]{font-weight: bold}/*所有具有title和href属性的a元素字体加粗*/
具体属性值选择
planet[moons="1"]{font-weight: bold;}/*所有具有moons属性值等于1的planet元素字体加粗*/
部分属性值选择
*[foo^="bar"] /*选择fool属性值以bar开头的所有元素*/
*[foo$="bar"] /*选择fool属性值以bar结尾的所有元素*/
*[foo*="bar"] /*选择fool属性值包含bar子串的所有元素*/
*[foo~="bar"] /*选择fool属性值包含bar的所有元素*/
特定属性选择类型
[att|="val"],这个规则会选择att属性为值为val和val-开头的所有元素
*[lang|="en"] /*选择lang属性值为en和en-开头的所有元素*/
后代选择器
选择后代元素
后代选择器中间用空格隔开,后一元素是前一元素的后代。
h1 em{color:red} /*选择h1的所有em后代元素*/
blockquot b,p b{color:gray}/*组合选择。选择blockquot的后代中所有b元素,选择p的后代中所有b元素。*/
选择子元素
用 > 标识
h1>strong {color:green} /*选择和h1的子元素strong,而不是h1后代元素*/
选择相邻兄弟元素
用 + 标识
h1+p{margin-top: 0;}/*选择h1元素后的p元素,他们有相同的父元素*/
后代选择器综合
html > body table + ul {margin-top: 1.5em;}
选择在table后的出现的所有兄弟ul元素,该table包含在一个body元素中,body元素本身是html的子元素。
伪类选择器
链接伪类
a:link 指向未访问的a标签
a:visited 指向访问的a标签
a:link{color: blue}
a:visited{color: red}
动态伪类
:focus 指示当前输入焦点的元素
:hover 鼠标指针停留的元素
:active 用户输入激活的元素
伪类的顺序:link-visited-focus-hover-active
动态伪类可以应用到任何元素
input:focus{background: silver;font-weight: bold;}/*选择点击的input元素*/
选择第一个子元素
:first-child
p:first-child{font-weight: bold}/*选择p元素作为第一个子元素的p元素*/
根据语言选择
*:lang(fr){font-style: italic}/*该选择器与|=属性选择器一样*/
结合伪类
a:link:hover{color: red}
a:visited:hover{color: maroon}
伪元素选择器
:first-letter
:first-line
:before
:after
h2:first-letter{font-size: 200%} /*选择h2的首字母*/
p:first-line{color: purple}/*p元素的第一行*/
h2:before{content: "test "}/*h2前加入test字符*/
h2:after{content: " the end";}/*h2后面加入the end 字符*/