CSS3属性选择器特性使用详解

techbrood 发表于 2017-02-21 18:15:59

标签: css3, selector, attribute, 基础知识, 入门教程

- +

CSS3除了引入动画、滤镜(用于特效)以及新的布局技术外,在选择器(selector)方面也有增强。

属性选择器根据元素的属性(attributes)来匹配。这可以是一个单独的属性,比如[type],或者可以是一个属性和取值的组合,比如[type=checkbox] 或 [for="email"]。

我们也可以用属性选择器来匹配属性存在与否以及子字符串。例如,我们可以在空格分隔开的列表中匹配属性值,或者我们可以匹配以字符串tel:开始的属性值。我们甚至可以匹配带连字符的属性值如en-US。其中连字符匹配和空格分隔属性值列表匹配早在CSS2中已有定义。

CSS3的增强在于添加了部分(partial)匹配规则。本篇将着重介绍新引入的属性选择器(Attribute selectors)使用方法。

部分匹配

使用全属性值来匹配是很常用的方法,不过在CSS3中我们可以使用部分匹配,语法格式是:

[att~=val]

这里att代表属性,val代表空格分隔开来的属性值列表中的某一个值。波浪线~表示部分匹配的语义。

比如:

<a href="http://techbrood.com/" class="html5 friends">techbrood</a>

我们可以使用[class~=friends]来匹配上述的a元素:

a[class~=friends] {
    font-size: 2em;
    background: #eee;
    padding: 4px;
    text-decoration: none;
    border-bottom: 3px solid #ccc;
}

以上方法适用于rel,data-*等以空格区分开来的属性值列表。

连字符匹配

对于类似en-US以连字符(-)连接起来的属性值,我们可以使用[attr|=val]来匹配。

比如以下HTML代码:

<article class="techbrood">
    <h3>techbrood lastest articles</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing ....</p>
</article>

<article class="techbrood-html5">
    <h3>techbrood latest articles on html5</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing ....</p>
</article>

<article class="techbrood-css3">
    <h3>techbrood latest articles on css3</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing ....</p>
</article>

我们可以使用[class|=techbrood]来匹配上面的3个article元素:

[class|="techbrood"] {border-top: 5px solid #4caf50;color: #555;line-height: 1.3;padding-top: .5em;}
子字符串匹配

我们还可以通过子字符串来匹配属性值,有点类似于正则表达式:

^=$=*=
从头部匹配从尾部匹配包含某子字符串

比如下面的html代码:

<a href="tel:+13588888888">Call techbrood online support</a>

我们可以使用如下代码来匹配:

[href^="tel:"] {
    background: #2196f3;
}

或者:

[href*="5888"] {
    background: #2196f3;
}

你可以自己在线试试看

possitive(14) views6522 comments0

发送私信

最新评论

请先 登录 再评论.
相关文章