CSS attribute selectors dig

CSS selectors properties can be matched by the element attribute name or attribute value already exists.

Attribute selector is introduced in CSS2 obtained and expanded in a well in CSS3. This article will introduce more comprehensive attribute selectors, as much as possible to tap the different uses of the selectors in different scenarios.

Simple syntax description

  • [Attr]: This selector selects the attributes attr containing all the elements, regardless of what the value of attr.
  • [Attr = val]: The selector selects only attr attribute is assigned to all elements of val.
  • [Attr ~ = val]: The selector selects only the elements having attributes attr, val value and require space-separated list of values ​​to be included in the value of attr one.

Substring value (Substring value) attribute selectors,

Several new CSS3 belonging to the following grammar, also referred to as "pseudo-regular Selector", because they provide a similar flexible regular expression matching.

  • [Attr | = val]: attr selection value or attribute value is val elements at the beginning Val- (note that here, "-" is not an error, which is used to process the language code).
  • [Attr ^ = val]: attr attribute selection value to begin with val (val comprise) elements.
  • [Attr $ = val]: selecting values ​​of attributes attr end with Val (including val) elements.
  • [Attr * = val]: Select the element values ​​included in attributes attr substring of val (a substring of a string that is part of them, for example, "cat" is the string "caterpillar" substring

CSS attribute selectors most basic usage

Attribute selectors most basic usage is through the attribute value of the element to select DOM elements. As such, all with the selected hrefDOM element attributes:

[href] {
    color: red;
}
复制代码

CodePen Demo - attribute selectors basic usage

A little bit complicated usage

Select stacked

div [href]{
...
}

复制代码

And more complex selection conditions

Img select a label, which contains a title attribute and an element comprising a class named logo.

img[title][class~=logo]{
...
}
复制代码

Pseudo-canonical writing

  • i parameter

Ignore capitalization limit class name, select the class that contains the class name contains the substring is p element text, Text, TeXt ... and other conditions. I here is the meaning of meaning inside the regularization parameter i, ignore, ignore case mean.

p[class*="text" i] {
...
}
复制代码

So the above selectors can select the target element like this:

<p class="text"></p>
<p class="nameText"></p>
<p class="desc textarea"></p>
复制代码
  • g parameter

Regular expression is not the same, the parameter grepresented here case sensitive (case-sensitively). However, this property has not yet incorporated into the current standard , not much supported browser.

CodePen Demo - attribute selectors pseudo regular usage

With the :not()pseudo-class

Another scenario is more commonly used with :not()pseudo-classes, some of the detection of the completion determining function. For example, the following selector can not select all the [href]attributes of athe tag, adding a red border.

a:not([href]){
    border: 1px solid red;
}
复制代码

Of course, more complex, we can not with a :not()pseudo-class, like this, can be used in conjunction with multiple simultaneously, select a href, target, rel attributes are not a label:

a:not([href]):not([target]):not([rel]){
    border: 1px solid blue;
}
复制代码

CodePen Demo - attribute selector with: not pseudo-class

Rewrite inline styles?

Even peace, if there is such a scenario, we can also override the inline style, like this:

<p style="height: 24px; color: red;">xxxxxx</p>
复制代码

We can use attribute selectors to force overwrite the above style:

[style*="color: red"] {
    color: blue !important;
}
复制代码

Use a combination of punches, with pseudo-elements enhance the user experience

Of course, not necessarily just simply attribute selector is selected tag.

With the pseudo-elements, we can achieve a lot of help to enhance the function of the user experience.

Subscript function

There is a little knowledge, pseudo-element contentproperties, by attr(xxx), can read the values corresponding DOM element tag named attribute xxx.

So, with the attribute selector, we can easily achieve some angle standard features:

<div count=“5“>Message</div>
复制代码
div {
    position: relative;
    width: 200px;
    height: 64px;
}

div::before {
    content: attr(count);
    ...
}
复制代码

Here the subscript numeral 5 prompts the upper right corner, is to use the pseudo-attribute selector mating elements to achieve, can be adapted to various lengths, and in English, it is possible to save some labels. CodePen Demo - attribute selector function implemented subscript

Attribute selector element with pseudo-function implementing class title

We all know that if a picture to add a title attribute, when hover the picture above will show additional content inside the title attribute, like this:

<img src="xxxxxxxxx" title="风景图片">
复制代码

Here is not necessarily a imglabel, other labels add titleattributes can have a similar effect. But there are two problems here:

  • Response is too slow, usually a mouse hover up to about 1s will appear every frame of this title
  • Frame structure can not be customized, pop-up box styles can not be customized

So here, if we want to have some blanket may be able to control their rapid response pattern, can customize a title attribute class, we call it popTitle, you can do this:

<p class="title" popTitle="文字弹出">这是一段描述性文字</p>
<p class="title" popTitle="标题A">这是一段描述性文字</p>
复制代码
p[popTitle]:hover::before {
    content: attr(popTitle);
    position: absolute;
    color: red;
    border: 1px solid #000;
    ...
}
复制代码

Compare the first native carrying titleproperties, the following two properties are used to select the pseudo-element simulation mating tips:

Browser carrying titleproperty stabilization delay response is to add a layer of protection against frequent triggering herein can also add to a 100 millisecond pseudo-element transition-delaydelay is implemented impressions.

CodePen Demo - attribute selector element with pseudo-function implementing class title

Merchandise display prompt effect

Well, using the above example we'll expand it, to consider how best to use actual business, there is also a lot of useless. Instance, add tags to pictures by attribute selectors, a similar effect of some electric provider website will be used.

We want to give the picture to add some tags to show up in the picture when hover.

Of course, CSS, such as <img>, , <input>, <iframe>these tags are not supported by pseudo-elements.

So here we output the DOM, to img parent element to bring part of the picture description tag. By CSS to control the display of these tags:

<div class="g-wrap" desc1="商品描述AAA" desc2="商品描述BBB">
    <img src="https://xx.baidu.com/timg?xxx" >    
</div>
复制代码
[desc1]::before,
[desc2]::after {
    position: absolute;
    opacity: 0;
}

[desc1]::before {
    content: attr(desc1);
}

[desc2]::after {
    content: attr(desc2);
}

[desc1]:hover::before,
[desc2]:hover::after{
    opacity: 1;
}
复制代码

Look at the results:

CodePen Demo - add tags to pictures by attribute selectors

Attribute selectors with pseudo-elements to achieve the download prompt

We know, HTML5 tag adds a download attribute, which instructs the browser to download a URL instead of navigating to it.

So, we can prompt all elements with such labels using attribute selectors. like this:

<a href="https://www.xxx.com/logo.png" download="logo">logo</a>
复制代码
[download] {
    position: relative;
    color: hotpink;
}

[download]:hover::before {
    content: "点击可下载此资源!";
    position: absolute;
    ...
}
复制代码

When we hover link to this time, this will prompt the user, this is a button that can be downloaded:

CodePen Demo - attribute selectors with pseudo-elements do download prompt

Attribute selector with dummy elements of the link protocol tips (http / https)

Now most of the website is not cut https https is to walk in the road cut. If the link on the page or have a lot of requirements, using the property selectors with pseudo-element tips may well be a good way to link the protocol to the agreement of the jump page.

a[href^="http:"]:hover::before {
    content: "这是一个http链接";
    ...
}

a[href^="https:"]:hover::before {
    content: "这是一个https链接";
}
复制代码

CodePen Demo - attribute selector elements with dummy link protocol prompts (http / https)

Of course, the content of pseudo-elements is not necessarily plain text, in order to give the user a better experience, or drawing pictures and text are possible.

For example, we can visualize the link to https site plus a small green lock, in line with some general knowledge of the user.

Here I will use images of little green lock base64 embedded pseudo-elements, a simple to use text-indentcontrol graphic arrangement:

a[href^="https:"]:hover::before {
    content: "";
    padding-left: 16px;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAb0lEQVQoz2NkQAJc5aIc//7962VgYIiDCi1iYmIq/tb5+gdMDROyBqhiGWYmJlVmJiZVBgYGGagYdsBRKvyZu1xUAsbnLheV4CgV/oxbQ4nwf0JiTAwkAkaIU4QaGf4z1uFX+b/pR/e7epJtGJEaAKDXHzEJ3KYmAAAAAElFTkSuQmCC");
    ...
}
复制代码

Here are just a very small Demo, the reality is that most users do not understand the meaning of this little green lock, so the actual use should assist with text prompts.

CodePen Demo - attribute selector elements for mating the dummy graphic prompt https protocol

Attribute selector handle a file type

It can also be carried out icon on the visual cue for some downloadable resources.

<ul>
    <li><a href="xxx.doc">Word File</a></li>
    <li><a href="xxx.ppt">PPT File</a></li>
    <li><a href="xxx.PDF">PDF File</a></li>
    <li><a href="xxx.MP3">MP3 File</a></li>
    <li><a href="xxx.avi">AVI File</a></li>
</ul>
复制代码
a[href$=".doc" i]::before {
    content: "doc";
    background: #a9c4f5;
}
a[href$=".ppt" i]::before {
    content: "ppt";
    background: #f8e94f;
}
a[href$=".pdf" i]::before {
    content: "pdf";
    background: #fb807a;
}
a[href$=".mp3" i]::before {
    content: "mp3";
    background: #cb5cf5;
}
a[href$=".avi" i]::before {
    content: "avi";
    background: #5f8ffc;
}
复制代码

CodePen Demo - attribute selectors to select the file name suffix

Attribute selector to inputthe type of processing

Attribute selectors fact, inputthe type of element is a good helper, as inputusual, and often with a lot of property values for different functions.

But, due to the inputtype of pseudo-elements can not be added. So with more attribute selector to change their state by various style attributes.

A simple example, such as:

<input type="text">
<input type="text" disabled>
复制代码
input[type=text][disabled] { 
    border: 1px solid #aaa;
    background: #ccc; 
}
复制代码

Here, we have chosen type=textand have disabledthe properties of inputthe elements, it will be the background color and border color to gray. Give users a better visual cue.

It is noteworthy point

Note selector priority, .classand [class=xxx]whether equivalence

Consider this issue, the following two selectors whether or equivalent?

<div class="header">
复制代码
.header {
    color: red;
}

[class~="header"] {
    color: blue;
}
复制代码

It said two selectors, exactly the same effect. However, if it is following this case, two is not the same:

<div id="header">
复制代码
#header{
    color: red;
}

[id="header"] {
    color: blue;
}
复制代码

Here, the selector ID #headerthan attribute selectors [id="header"]right weight higher, although both the same elements can be selected, but the two are not exactly equivalent.

The need for quotation marks?

Consider the following three cases, are the same?

[class="header"]{ ... }

[class='header']{ ... }

[class=header]{ ... }
复制代码

In fact, from HTML2 start, do not add quotation marks wording has to be supported, so all three versions are correct.

However, without using quotation marks is limited, look at the following written in this way:

a[href=bar] { ... }

a[href^=http://] {... }
复制代码

The second option is invalid selectors, ://does not come, then will cause recognition errors, you must use quotation marks like this a[href^="http://"], where specific reasons can read this article: unquoted attribute value Validator .

So the safe side, we recommend that all quotation marks.

CSS semantic

Write "with a semantic HTML" principle is the basis for a modern, professional front-end development. Of course, we often talk about is semantic HTML.

So, CSS semantic need? CSS semantic issue? Examples of the above-described example, the use of a specific class name or id selector Jieke completed. So what reason to use attribute selectors are?

I understand that the attribute (attribute) itself has a certain semantic expression of certain features or functional element, then the element selected by using the attribute values ​​of the attributes of a particular operation to some extent may also improve the secondary semantic code of. At least enhance the readability of CSS code. However, the need for semantic CSS this problem is a matter of opinion.

At last

Here are a few articles also covers many other aspects of use, can be compared watch:

CSS technology more exciting articles summarized in my Github - ICSS , continuously updated, welcome to subscribe to the point of a star collection.

Well, this is over, I hope to help you :)

If you have any questions or suggestions, you can interact more, original articles, writing is limited, ignorant, if the text is not correct place, Wan Wang told.

Reproduced in: https: //juejin.im/post/5d084b6651882563194b2eab

Guess you like

Origin blog.csdn.net/weixin_33933118/article/details/93163647