CSS 选择器

CSS 选择器分为:元素选择器、分组选择器、通配符选择器、类选择器、ID 选择器、属性选择器、后代选择器、子元素选择器、相邻兄弟选择器、伪类、伪元素。
 

 
一. 元素选择器(p)
 
选择器可以是 HTML 元素,比如 p、h2、body,甚至是 html 本身。
 
# code 1 # type selector 

<
style type="text/css"> body { margin: 0 auto; max-width: 50em; font-family: cursive, "Arial", sans-serif; line-height: 1.5; padding: 4em 1em; color: #555; } h2 { margin-top: 1em; padding-top: 1em; } h2, strong { color:#333; } </style> <body> <h2>《人类简史》书摘</h2> <p>金钱、社会地位、整形手术、豪宅、握有大权的职位,这些都不会给你带来<strong>快乐</strong>。想要有长期的快乐,只能靠血清素、多巴胺和催产素。</p> </body>
 

 
二. 分组选择器(h2, strong)
 
如果某些元素的样式是一样的,那可以把修饰这些样式的选择器,列为一组,选择器之间用逗号隔开。比如,# code 1 中我们就这样写了:
 
# code 2 # selector grouping

h2, strong
{ color:#333; }
 

 
三. 通配符选择器(*)
 
显示为一个星号(*),表示匹配任意一个元素。是 CSS2 引入的。
 
# code 3 # universal selector

*
{ box-sizing: border-box; text-rendering: geometricPrecision; }
 
通配符选择器可以看成是一个特殊的分组选择器,它是“列出了”文档中的所有元素进行的声明。
 

 
四. 类选择器(.)
 
一个点号(.)后面跟上类名,就是类选择器了。它可以单独使用,也可以和别的元素结合使用。
 
# code 4 # class selector

<
style type="text/css"> p.important { color:red; } h1.important { color:blue; } </style> <body> <h1 class="important">#人类简史</h1> <p class="important">今天,人类正在让许多物种灭绝,甚至可能包括自己。如果今天发生核灾而让世界末日降临,老鼠和蟑螂很有可能继续将自己的DNA传给千代万代。或许6500万年后,会有一群高智商的老鼠心怀感激地回顾人类造成的这场灾难,就像我们现在感谢那颗杀死恐龙的陨石一般。#书摘 </p> <p>是啊,对的.</p> <p>...</p> </body>

 

一个 class 值还可以包含一个词列表,各个词之间用空格分开:
 
# code 5 # mutiple class selector

<
style type="text/css"> .important { font-weight:bold; } .warning { font-style:italic; } .important.warning { background:silver; } </style> <body>
<p class="important">This paragraph is very important.</p> <p class="warning">This is a warning.</p> <p class="important urgent warning">This paragraph is a very important warning.</p> <p>This is a paragraph.</p> </body>
 
上面的选择器称为多类选择器。
 

 
五. ID 选择器(#)
 
ID 选择器类似于类选择,不过也有一些差别:
 
1). ID 选择器以 # 号开头;
 
2). ID 选择器引用 id 属性中的值;
 
# code 6 # ID selector

<
style type="text/css"> #intro { font-weight:bold; } </style> <body> <p id="intro">This is a paragraph of introduction.</p> <p>This is a paragraph.</p> <p>...</p> </body>
 
那 ID 选择器与类选择器有哪些不一样的地方呢?
 
1). 一个 id 值在 HTML 文档里只能用在一个元素上。这不同于 class 的值,上面我们讲到类选择器时,类名 important 被用到 p 和 h1 元素上,其实 important 还可以应用到更多的元素上,它修饰具有相同样式的一类元素。而一个 id 值唯一标记 HTML 文档里的一个元素!
 
2). 与类属性不同的是,ID 属性值不可以是词列表,这一点应该很好理解。
 
......
 
它是错的,一个 id 值唯一标记 HTML 文档里的一个元素。
 

 
六. 属性选择器([])
 
根据元素的属性或属性值,来选择元素,CSS2 引入。
 
将包含 title 属性的所有元素颜色设置为红色:
 
# code 8 # attribute selector

*[href]
{ color: red; }
 
只对有 href 属性的 a 元素应用样式:
 
# code 9 # attribute selector

a[href]
{ color: red; }
 
还可以根据多个属性进行选择,只需要将属性选择器连接在一起就可以了:
 
# code 10 # mutiple attribute selector

a[href="http://www.ruanyifeng.com/"][title="Ruan YiFeng"]
{ color: red; }
 
根据属性值进行选择:
 
# code 11 # 将 moons 属性值为 1 的 planet 元素里的文本颜色设置为红色

planet[moons="1"] { color: red; }
 
如果属性值是个值列表,还用 = 进行匹配的话,那么必须要与属性值完全匹配才行:
 
# code 12 # class must equal

......
p[class="important warning"] { color: red; } ......
<p class="important warning">This paragraph is a very important warning.</p>

......
 
问题来了,一定要与属性值完全匹配吗?不是的,看下面:
 
# code 13 # part of the attribute selectors

......
p[class~="important"]
{ color: red; } a[title~="Ruan YiFeng"] { border: 1px solid gray; }

......

<a title="Ruan YiFeng">link.</a>

......
 
我们用 "~=" 来实现部分属性值的匹配,这称为部分值属性选择器
 
在 CSS2 之后,还发布了更多的部分值属性选择器,其中就有“子串匹配属性选择器”,包括 IE7 在内的许多浏览器都支持的,下面是这些选择器的简单总结:
 
类型 描述
[abc^="def"] 选择 abc 属性值以 "def" 开头的所有元素
[abc$="def"] 选择 abc 属性值以 "def" 结尾的所有元素
[abc*="def"] 选择 abc 属性值包含子串 "def" 的所有元素
# code 14 # substring matching selectors

a[href*="ruanyifeng.com"]
{ color: red; }
 
最后为你介绍,特定属性选择器 "|="
 
# code 15 # specific selectors

...... *[lang|="en"] { color: red; } ......
<p lang="en">Hello!</p> <p lang="en-us">Greetings!</p> <p lang="en-au">G'day!</p> <p lang="fr">Bonjour!</p> <p lang="cy-en">Jrooana!</p> ......
 
这里会匹配 lang 属性的值为 en 或以 en 开头的所有元素。
 
一般来说,[att|="val"] 可以用于任何属性及其值,但最常见的用途还是匹配语言值。
 
img[src|="figure"] {
    border: 1px solid gray;
}
 

 
七. 后代选择器(这里假装有个空格)
 
Descendant Selector,如果你希望对 ul 元素中的 em 使用样式,可以这样写:
 
# code 16 # descendant selector

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Descendant Selector Test</title>
    <style type="text/css">
        ul em {
            color:red; 
            font-weight:bold;
        }
    </style>
</head>
<body>

    <ul>
        <li>List item 1
            <ol>
                <li>List item 1-1</li>
                <li>List item 1-2</li>
                <li>List item 1-3
                    <ol>
                        <li>List item 1-3-1</li>
                        <li>List item <em>1-3-2</em></li>
                        <li>List item 1-3-3</li>
                    </ol>
                </li>
                <li>List item 1-4</li>
            </ol>
        </li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ul>

</body>
</html>
 
代代之间用空格分开。上面的 em 元素不管嵌套的层数,样式效果始终对它有效。ul em 可以理解成“作为 ul 元素后代的任何 em 元素”。
 

 
八. 子元素选择器(>)
 
相比后代选择器对所有后代生效,子元素选择器(用 >)只对子元素有效,或者说只对“儿子”有效。
 
看,与上面 # code 16 的代码一样,样式生效的只有“儿子”。
 
下面,是结合后代选择器和子选择器的例子:
 
# code 17 # child selectors

table.company td > p
 
这个选择器选择了 p 元素进行样式渲染,这个 p 元素是 td 的子元素,而 td 是类名为 company 的 table 元素的后代。
 

 
九. 相邻兄弟选择器(+)
 
如果要选择紧接在另一个元素后的元素(二者有相同的父元素),可以使用相邻兄弟选择器(Adjacent sibling selector)。
 
例如,如果要增加紧接在 h1 元素后出现的段落的上边距,可以这样使用:
 
# code 18 # adjacent sibling selector

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Adjacent Sibling Selector Test</title>
    <style type="text/css">
        h1 + p {
            margin-top:50px;
        }
    </style>
</head>
<body>
    <h1>549吨洋垃圾衣服 - 2016.8.12</h1>
    <p>这批衣服中绝大多数来自国外太平间、垃圾站、废品收购站。.</p>
    <p>记者从衣服堆里面拎起一件厚实的外套,在上面发现一所韩国学校的标志,在这件深蓝色校服上还可以清晰看到一个学生的名字。.</p>
    <p>在国外收集这些衣物几乎是零成本。“从国外运来,再以每一吨1000元(在国内)卖出去,金额达到1100万元。”</p>
    <p>不法商家买到旧衣物后进行翻新,再以“超低价格”、“外贸尾货”、“出口转内销”等名义销售,受到部分青少年青睐。.</p>
    <p>“在深圳龙岗、宝安,特别是布吉、西乡一带的小店里,有些牛仔裤每条才卖15元,谁知道这些货来自哪里。”.</p>
    <p>嫌疑人运货“月薪”8500元.</p>
    <p>官兵们都登上目标船后,把货物掀开,发现是一些废旧衣服,一股消毒水的刺鼻味道迎面扑来。“估计他们也怕这些废旧物品有病菌、病毒,先进行第一次消毒。”</p>
</body>
</html>
 
用一个结合符,只能选择两个相邻兄弟中的第二个元素,请看下面的例子:
 
# code 19 # adjacent sibling selector

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Adjacent Sibling Selector Test</title>
    <style type="text/css">
       li + li {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <h2>Web Design in 4 Minutes <a href="http://jgthms.com/">@jgthms</a></h2>
    <div>
        <ol>
            <li>Content</li>
            <li>Centering</li>
            <li>Font family</li>
            <li>Spacing</li>
            <li>Color &amp; contrast</li>
            <li>Balance</li>
            <li>Primary color</li>
            <li>Secondary colors</li>
            <li>Custom font</li>
            <li>Graphcis &amp; icons &amp; header...</li>
        </ol>
    </div>
</body>
</html>
 
上面的这个选择器,只会把第二个之后的列表项设置为粗体,第一个列表项不受影响。
 

 
十. 伪类(:link)
 
先让我们来看一下,伪类有哪些。
 
:link       未被访问的链接的样式
:visited  已被访问的链接的样式
:hover    当鼠标悬浮在元素上方时,元素的样式
:active   被激活的元素样式
:focus    处于输入焦点状态的元素样式
:first-child 父元素的第一个子元素的样式
:lang      为不同的语言定义特殊的样式
 
这是伪类的语法:
selector : pseudo-class { property: value }
或者(类与伪类搭配):
selector.class : pseudo-class { property: value }
 
下面我们来对上面所列举的伪类,进行说明。
 
链接的不同状态(未访问、已访问、鼠标悬停、活动)可以有不同的显示样式:
 
# code 20 # pseudo classes

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-classes Test</title>
    <style type="text/css">
        a:link { color: #FF0000 }
        a:visited { color: #00FF00 }
        a:hover { color: #FF00FF }
        a:active { color: #0000FF }
    </style>
</head>
<body>
    <p><a href="/index.html" target="_blank">这是一个链接。</a></p>
    <p>在 CSS 定义中,a:hover 必须位于 a:link 和 a:visited 之后,这样才能生效!</p>
    <p>在 CSS 定义中,a:active 必须位于 a:hover 之后,这样才能生效!</p>
</body>
</html>
 
为了能让链接的样式相称的显示出来,你必须按照这样的顺序去定义样式::link —— :visited —— :hover —— :active。
 
可以使用 :first-child 伪类,来选择所处父元素的第一个子元素:
 
# code 21 # pseudo classes

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-classes Test</title>
    <style type="text/css">
        p:first-child { font-weight: bold; }
        li:first-child { text-transform:uppercase; }
    </style>
</head>
<body>
    <div>
        <p>These are the necessary steps:</p>
            <ul>
                <li>Intert Key</li>
                <li>Turn key <strong>clockwise</strong></li>
                <li>Push accelerator</li>
            </ul>
        <p>Do <em>not</em> push the brake at the same time as the accelerator.</p>
    </div>
</body>
</html>    

 

上面的样式是在匹配第一个 p 元素和 li 元素不是“选择 p 元素的第一个子元素、li 元素的第一个子元素”,这是大家常常误解的地方。
 
下面是匹配第一个 p 元素里的 em 元素:
 
# code 20 # pseudo classes

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-classes Test</title>
    <style type="text/css">
        p:first-child em { 
            font-weight: bold; 
        }
    </style>
</head>
<body>
    <p>some <em>text</em>. some <em>text</em>.</p>
    <p>some <em>text</em>. some <em>text</em>.</p>
</body>
</html>
 
:lang 伪类使你有能力为不同的语言定义特殊的规则:
 
# code 20 # pseudo classes

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-classes Test</title>
    <style type="text/css">
        q:lang(no) {
            quotes: '「' '」';
        }
    </style>
</head>
<body>
    <p>海明威说<q lang="no">任何初稿,都是一堆臭狗屎</q></p>
</body>
</html>

<html>
<head>

 

我们为 lang 属性值为 no 的 q 元素指定了引号的类型。
 

 
十一. 伪元素(:first-letter)
 
伪元素与伪类相似,它有些这些选项:
 
:first-letter  文本第一个字母的样式
:first-line     文本第一行的样式
:before        在元素之前添加内容
:after           在元素之后添加内容
 
伪元素的语法与伪类一样:
selector:pseudo-element { property:value; }
或者
selector.class:pseudo-element { property:value; }
 
下面,我们还是按部就班的,对上面的伪元素进行说明。
 
我们用 first-letter 对 p 元素的第一个字母设置样式:
 
# code 21 # pseudo element

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-element Test</title>
    <style type="text/css">
        p:first-letter {
            font-size: 2em;
        }
    </style>
</head>
<body>
    <p>You can use the :first-letter pseudo-element to add a special effect to the first letter of a text!</p>
</body>
</html>
 
注意:first-letter 只能用于块级元素, 可以应用下面的属性:
  • font
  • color
  • background
  • margin
  • padding
  • border
  • text-decoration
  • vertical-align (仅当 float 为 none 时)
  • text-transform
  • line-height
  • float
  • clear
再用 first-line 对 p 元素的第一行文本设置样式:
 
p:first-line {
    color: #ff0000;
    font-variant: small-caps
}
 
注意:first-line 只能用于块级元素, 可以应用下面的属性:
  • font
  • color
  • background
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear
下面同时使用 first-letter、first-line 对 p 元素的样式进行设置(伪元素可以与 CSS 类配合使用):
 
# code 21 # pseudo element

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pseudo-element Test</title>
    <style type="text/css">
        p.article:first-letter {
            color:#ff0000;
            font-size:xx-large;
        }

        p.article:first-line {
            color:#0000ff;
            font-variant:small-caps;
        }
    </style>
</head>
<body>
    <p id="article">This is a paragraph in an article。</p>
    <p id="article">This is a another paragraph in an article。</p>
</body>
</html>
 
:before 和 :after
 
h1:before { content:":)" }
h1:after { content:":(" }
 
 
(完)
posted @ 2016-08-12 12:00  Hi!张宝  阅读(304)  评论(0编辑  收藏  举报