CSS property selector, which matches elements with existing property names or property values.

Property selectors were introduced in CSS2 and have been greatly expanded in CSS3. This article will give a comprehensive introduction to the property selector, and try to explore the different uses of the selector in different scenarios.

Simple syntax introduction

  • [attr] : This selector selects all elements that contain the attr attribute, regardless of the value of attr.
  • [attr=val] : This selector selects only all elements whose attr attribute is assigned to val.
  • [attr~=val] : This selector selects only elements that have an attr attribute and requires val to be one of the space-separated values in the list of values that attr contains.

Substring Value property selector,

The following are some of the new CSS3 syntax additions, also known as “pseudo-regular selectors” because they provide flexible matching similar to regular expression.

  • [attr | = val] : the selection of the attr attribute value is val or to val – at the beginning of elements (note that the “-” is not a mistake here, this is used for processing language code).
  • [attr^=val] : Selects elements whose values of the attr attribute start with val (including val).
  • [attr$=val] : selects elements whose values of the attr attribute end in val, including val.
  • [attr*=val] : Selects the element whose value of the attr attribute contains the substring val (a substring is just part of a string, for example, “cat” is a substring of the string “caterpillar”

The basic use of CSS property selectors

The most basic use of attribute selectors is to select DOM elements by their attribute values. All DOM elements with href attribute are checked like this:

[href] {
    color: red;
}
Copy the code

CodePen Demo – Basic use of property selectors

A little bit more complicated usage

Cascading selection

div [href]{
...
}

Copy the code

Multiple conditional compound selection

Select an IMG tag that contains the title attribute and an element with the class name LOGO.

img[title][class~=logo]{
...
}
Copy the code

Pseudo regular notation

  • iparameter

Ignore case restrictions on class names and select include class. The class name contains substrings text, text, text… And so on. The “I” is the same as the “I” parameter in the re. Ignore and ignore case.

p[class*="text" i] {
...
}
Copy the code

So the above selector can select a target element like this:

<p class="text"></p>
<p class="nameText"></p>
<p class="desc textarea"></p>
Copy the code
  • gparameter

Unlike regular expressions, the parameter G here stands for case-sensitively. However, this property is not currently included in the standard and is not supported in many browsers.

CodePen Demo — Pseudo-regular usage of property selectors

Cooperate with:not()pseudo-classes

Another common scenario is the collocation :not() pseudo-class, which performs some judgment and detection functions. This selector, for example, takes all a tags that have no [href] attribute and adds a red border.

a:not([href]) {border: 1px solid red;
}
Copy the code

Of course, to make things more complicated, we can use more than one :not() pseudo-class, such as this, to use multiple of them at the same time, selecting an A tag that doesn’t have an href, target, or rel attribute:

a:not([href]):not([target]):not([rel]) {border: 1px solid blue;
}
Copy the code

CodePen Demo — Property selector matches :not pseudo class

Overwrite inline styles?

Even if we have this scenario, we can override inline styles like this:

<p style="height: 24px; color: red;">xxxxxx</p>
Copy the code

We can force the above styles to be overridden using the property selector:

[style*="color: red"] {
    color: blue ! important;
}
Copy the code

Combination of use, with false elements to improve user experience

Of course, attribute selectors don’t have to be solely for tag selection.

With fake elements, we can implement many features that will improve the user experience.

Angle of the function

Attr (XXX) can be used to read the value of the property named XXX corresponding to the DOM element tag.

Therefore, with the attribute selector, we can easily implement some corner functions:

<div count="5">Message</div>
Copy the code
div { position: relative; width: 200px; height: 64px; } div::before { content: attr(count); . }Copy the code

Here the number 5 in the upper right corner of the tip corner, is using the property selector with pseudo-element implementation, can adapt to various lengths, as well as Chinese and English, can save some tags. CodePen Demo — Property selector implements corner marking

Property selectors work with pseudo-elements to implement title-like functionality

We all know that if we add a title attribute to an image, it will display the content attached to the title attribute when it hover on the image, something like this:

<img src="xxxxxxxxx" title="Landscape pictures">
Copy the code

This doesn’t have to be an IMG tag, but any tag with a title attribute can have a similar effect. But there are two problems:

  • The response is too slow, usually mouse hover up to every 1s or so will appear the title box
  • The frame structure cannot be customized, and the pop-up style cannot be customized

So here, if we want to have some quickly responsive floating layer that we can control the style of, we can define a title class property called popTitle, then we can do something like this:

<p class="title" popTitle="Text pops up">This is a descriptive paragraph</p>
<p class="title" popTitle=Title "A">This is a descriptive paragraph</p>
Copy the code
p[popTitle]:hover::before { content: attr(popTitle); position: absolute; color: red; border: 1px solid #000; . }Copy the code

For comparison, the first one is the native title property, and the following two are hints for using the property selector in conjunction with the pseudo-element simulation:

The browser’s built-in title attribute delay response is to add a layer of anti-shake protection to avoid frequent triggering. You can also add a 100-millisecond transition-delay to the pseudo-element to achieve the delay display.

CodePen Demo – Property selector with pseudo element to implement class title functionality

Product display prompt effect

Good, the above application example we will expand, consider how to better apply to the actual business, in fact, there are many places to use. For example, you can tag an image with a property selector, similar to what some e-commerce sites use.

We want to add some tags to the images and display them when hover images.

Of course, CSS tags such as , , and

So here we export the DOM with a partial image description tag for the parent element of img. Use CSS to control the display of these tags:

<div class="g-wrap" desc1=Product Description AAA desc2="Product Description BBB">
    <img src="https://xx.baidu.com/timg?xxx" >    
</div>
Copy the code
[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;
}
Copy the code

Look at the results:

CodePen Demo – Tag images with property selectors

Property selectors work with pseudo-elements to implement download prompts

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

We can then use the attribute selector to prompt all elements with such tags. Like this:

<a href="https://www.xxx.com/logo.png" download="logo">logo</a>
Copy the code
[download] { position: relative; color: hotpink; } [download]:hover::before {content: "Click to download this resource!" ; position: absolute; . }Copy the code

When we hover to this link, it will do so, reminding the user that this is a downloadable button:

CodePen Demo – Property selector with pseudo element for download hints

Attribute selectors with pseudo-elements hint at the protocol of the link (HTTP/HTTPS)

Most websites now either cut HTTPS or are on their way to cutting HTTPS. If there are a lot of links on the page or there is a requirement for the protocol to jump to the page, it is also a good idea to use attribute selectors with pseudo-elements to indicate the protocol to link to.

A [href^=" HTTP :"]:hover::before {content: "this is an HTTP link "; . } a[href^=" HTTPS :"]:hover::before {content: "this is an HTTPS link "; }Copy the code

CodePen Demo — Attribute selector with pseudo element to hint for link protocol (HTTP/HTTPS)

Of course, the content of pseudo elements is not necessarily pure text. In order to give users a better experience, it is also possible to add text to pictures or pictures.

For example, we can visually add a small green lock to an HTTPS linked site, which conforms to some of the common perceptions of users.

Here, I embed the picture of the little green lock in the pseudo-element using Base64, and simply use text-indent to control the layout of the text and text:

a[href^="https:"]:hover::before { content: ""; padding-left: 16px; background: url("data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAb0lEQVQoz2NkQAJc5aIc//7962VgYIiDCi1iY mIq/tb5+gdMDROyBqhiGWYmJlVmJiZVBgYGGagYdsBRKvyZu1xUAsbnLheV4CgV/oxbQ4nwf0JiTAwkAkaIU4QaGf4z1uFX+b/pR/e7epJtGJEaAKDXHzEJ3 KYmAAAAAElFTkSuQmCC"); . }Copy the code

This is only a very small Demo, the fact is that most users do not understand the meaning of the small green lock, so the actual use should be accompanied by text assistance.

CodePen Demo — Attribute selector with pseudo element for graphic hints of HTTPS protocol

Property selector handling of file types

Some downloadable resources can also be visually icon prompts.

<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>
Copy the code
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;
}
Copy the code

CodePen Demo — Property selector selects filename suffix

Property selector pairsinputType handling

An attribute selector is actually a great helper for input elements, because input is often used and often matches attribute values for many different functions.

However, you cannot add pseudo-elements because of the input type. So collocative property selectors are more likely to style themselves through the various states of the property.

Here’s a quick example:

<input type="text">
<input type="text" disabled>
Copy the code
input[type=text][disabled] { 
    border: 1px solid #aaa;
    background: #ccc; 
}
Copy the code

Here, we select the input element with type=text and the disabled attribute, and set its background color and border color to gray. Give users better visual cues.

Points worth noting

Note the selector priority,.class[class=xxx]Whether the equivalent

Consider the question, are the following two selectors equivalent?

<div class="header">
Copy the code
.header {
    color: red;
}

[class~="header"] {
    color: blue;
}
Copy the code

The above two selectors have exactly the same effect. However, the two are different when it comes to:

<div id="header">
Copy the code
#header{
    color: red;
}

[id="header"] {
    color: blue;
}
Copy the code

Here, the ID selector #header has more weight than the attribute selector [ID =”header”], and while both can select the same element, they are not completely equivalent.

Do I need quotes?

Consider the following three cases. Are they consistent?

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

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

[class=header]{ ... }
Copy the code

In fact, writing without quotes has been supported since HTML2, so all three are correct.

However, there are limits to being able to do without quotes, so look at this:

a[href=bar] { ... }

a[href^=http://] {... }
Copy the code

Unquoted attribute value validator () :// Unquoted attribute value validator () :// Unquoted attribute value validator

So to be on the safe side, use quotation marks.

CSS semantic

The principle of writing “semantic HTML” is a cornerstone of modern, professional front-end development. Of course, we’re always talking about HTML semantics.

So, does CSS need to be semantic? Does CSS have semantics? In the example above, either a specific class name or an ID selector can be used. So what’s the reason for using a property selector?

My understanding is that attributes themselves have certain semantics and express some features or functions of elements. Using attributes to select elements and then perform specific operations on the value of the attribute can also help to improve the semantics of the code to a certain extent. At the very least, it improves the readability of CSS code. But whether CSS needs to be semantically is a matter of opinion.

The last

Here are a few articles that also cover many other aspects of use and can be viewed in comparison:

  • Semantic CSS With Intelligent Selectors
  • HTML’s DNA With CSS Attribute Selectors

More interesting CSS technology articles are summarized in my Github — iCSS, constantly updated, welcome to click on the star subscription favorites.

Well, the end of this article, I hope to help you 🙂

If there are any questions or suggestions, you can exchange more original articles, writing is limited, talent and learning is shallow, if there is something wrong in the article, hope to inform.