1

CSS3 选择器

各种选择器你都知道吗?下面一一为你罗列一下。


1.标签选择器

标签选择器又叫元素选择器,换句话说,文档的元素就是最基本的选择器,使用元素名称直接选中元素即可。

例如 如下p标签即可直接选择

<style>
        p{
            height:100px;
            border:1px solid red;
        }
        
    </style>

    <p>one</p>
    <p>two</p>
    <p>three</p>

2.类选择器

类选择以点"."开头,后面紧跟一个类名。类名不允许有空格,与元素中class属性的值保持一致。一个元素可以有多个class的值,每个值通过空格分割开。类名相同的元素属于一类元素。

例如 如下class里面的类

<style>             
        .first{font-weight: bold;}             
        .done {text-decoration: line-through;}         
    </style>
    <ul>        
        <li class="first done">Create an HTML document</li>
        <li class="second done">Create a CSS style sheet</li>
        <li class="third done">Link them all together</li>        
    </ul>

3.ID选择器

ID选择器以"#"开头,后面紧跟一个ID名,在一个文档中,ID值不能重复,因此在选择文档中唯一元素的时候该选择器比较有用。

例如 如下id选择

<style>            
        #polite {      font-family: cursive;}            
        #rude {    font-family: monospace;     
                   text-transform: uppercase;}
    </style>
    
    <p id="polite"> — "Good morning."</p>        
    <p id="rude"> — "Go away!"</p>

4. 普遍选择器

使用“*”来表示普遍选择器,表示选择所有元素,通常用在组合选择器中。

例如 如下选择的就是left-nav的所有子元素

<style>            
        .left-nav > * { width:200px; background-color:#fafafa}
    </style>
    
    <article class="left-nav">
         <dl>                
            <dt>推荐</dt>                
            <dd class="current"><
            i class="icon-music"></i>发现音乐</dd>        
            </dl>            
        <dl>                
            <dt>我的音乐</dt>    
                <dd><i class="icon-cloud-download">
                </i>下载的音乐</dd>            
                </dl>
    </article>

5.层次选择器

  • 5.1后代选择器
使用 “ ” 隔开两个选择器。例如 “ul li”表示选择ul的后代元素li,li可以为ul的直接子元素,也可以为ul的孙子元素。
  • 5.2子代选择器
使用 “>” 隔开两个选择器。例如 "ul>li"表示选择ul的直接子代元素li,ul的孙子元素li无法被选择到
  • 5.3相邻同胞选择器
使用 “+” 隔开两个选择器。例如 ".one+*"表示选择class为"one"元素的下一个兄弟元素。
  • 5.4一般同胞选择器
使用 “~” 隔开两个选择器。例如 ".one~*"表示选择class为"one"元素的所有兄弟元素。

6.属性选择器

属性选择器有以下几种

clipboard.png

例如如下,就是选择button中具有name属性的元素并且name的值为del的元素

<style type="text/css">
        button[name=del]{
            border: 2px dotted #ccc;
        }
    </style>

<div class="container">
        <button class="addBtn" name="add">添加</button>
        <button class="delBtn" name="del">删除</button>
        <button class="updBtn" name="upd">更新</button>
        <button>搜索</button>
    </div>

7.伪类选择器

伪类以":"开头,用在选择器后,用于指明元素在某种特殊的状态下才能被选中
  • 7.1表示子元素

clipboard.png

  • 7.2 与状态相关

clipboard.png

伪元素选择器

伪元素以"::"开头,用在选择器后,用于选择指定的元素

clipboard.png


Quinty
6 声望6 粉丝

« 上一篇
HTML 基础入门