Translator: Front-end wisdom

Original: www.smashingmagazine.com/2018/10/att…

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Property selectors are amazing. They can get you out of tricky problems, help you avoid adding classes, and point out problems in your code. But don’t worry, while property selectors are very complex and powerful, they are easy to learn and use. In this article, we’ll discuss how they work and give some ideas on how to use them.

To read more quality articles pleaseJabber at the GitHub blog, a hundred quality articles a year waiting for you!

HTML attributes are usually placed in square brackets, called attribute selectors, as follows:

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

Any element with an href attribute that doesn’t have a more specific selector will have a red text color. Property selectors have the same properties as classes.

Note: For more on CSS specificity of cage matching, you can read CSS Features: Things You Should Know, or if you like Star Wars :CSS Feature Wars.

But you can do more with property selectors. Just like your DNA, they have internal logic to help you choose various attribute combinations and values. They can match any property in a property, even string values, rather than matching exactly like tags, classes, or ID selectors.

Property selector

Attribute selectors can exist independently. More specifically, if you need to select all div tags that have the title attribute, you can do this:

div[title]
Copy the code

But you can also select a child element of a div with the title attribute by doing the following

div [title]
Copy the code

To be clear, the lack of space between them means that the attribute is on the same element (just as there is no space between an element and a class), and the space between them means a descendant selector, which selects the children of the element that has that attribute.

You can more finely select attributes for specific attribute values.

div[title="dna"]
Copy the code

All divs with the exact name DNA were selected above, and while there are selector algorithms that can handle each case (and more), the title of ** “DNA is awesome” or “dnamutation” ** is not selected here.

Note: In most cases, quotes are not needed in property selectors, but I use them because I believe it improves the readability of clean code and ensures that boundary use cases work.

If you want to select the element whose title contains DNA, such as “My beautiful DNA” or “Mutating DNA is fun!” , you can use tilde (~).

div[title~="dna"]
Copy the code

They can handle some demanding jobs more easily. If you want to match a title that ends in DNA, such as “dontblamemeblamemyDNA” or “his- settlement-is-from-not-DNA”, you can handle some demanding jobs more easily using the $tag:

[title$="dna"]
Copy the code

If you want to match titles that start with DNA, such as “dnamutants” or “DNA-splicing -for-all”, just use the ^ identifier:

[title^="dna"]
Copy the code

While exact matching is helpful, it can be too tight, and the symbol matching can be too wide for your needs. For example, you might not want to choose the title “Genealogy”, but still select “gene” and “gene-data”. Characteristics of the pipe (|) is such, attribute must be complete and the only word, or by – separated.

[title|="gene"]
Copy the code

Finally, there is a fuzzy search attribute operator that matches any substring that does string splitting, as long as the word DNA can be separated:

[title*="dna"]
Copy the code

What makes these attribute selectors even more powerful is that they are stackable, allowing you to select elements with multiple matching factors.

If you need to find an A tag that has a title and a class ending in “genes”, you can do this:

a[title][class$="genes"]
Copy the code

Not only can you select attributes for HTML elements, you can also use pseudo-type elements to print out text:

<span class="joke" title="Gene Editing!" >What's the first thing a biotech journalist does after finishing the first draft of an article? </span>Copy the code


.joke:hover:after {
   content: "Answer:" attr(title);
   display: block;
}
Copy the code

The above code will display a custom string over the mouse.

The last thing to know is that you can add a flag to make property searches case-insensitive. Add I before closing square brackets:

[title*="DNA" i]
Copy the code

So it matches DNA, DNA, DNA, etc.

Now that we’ve seen how to use property selectors for selection, let’s look at some use cases. I divide them into two categories: general purpose and diagnostic.

General purpose

#### Input type style Settings

You can use different styles for input types, such as email and phone.

input[type="email"] {
   color: papayawhip;
}
input[type="tel"] {
   color: thistle;
}
Copy the code

#### displays phone links

You can hide phone numbers of a specific size and display phone links for easy calls on your phone.

span.phone {
   display: none;
}
a[href^="tel"] {
   display: block;
}
Copy the code

Internal links vs external links, secure links vs insecure links

You can discriminate between internal and external links and set secure links to be different from unsafe links:

a[href^="http"]{
   color: bisque;
}
a:not([href^="http"]) {
  color: darksalmon;
}

a[href^="http://"]:after {
   content: url(unlock-icon.svg);
}
a[href^="https://"]:after {
   content: url(lock-icon.svg);
}
Copy the code

#### Download icon

One of the attributes HTML5 gives us is “download,” which tells the browser, you guessed it, to download the file instead of trying to open it. This is useful for PDFS and docs that you want people to access but don’t want them to open immediately. It also makes the workflow of downloading a large number of files in a row easier. The downside of the download property is that there is no default visual effect to distinguish it from more traditional links. Usually this is what you want, but if not, you can do something like the following:

a[download]:after { 
   content: url(download-arrow.svg);
}
Copy the code

You can also use different ICONS (PDF versus DOCX versus ODF) to represent file types, and so on.

a[href$="pdf"]:after {
   content: url(pdf-icon.svg);
}
a[href$="docx"]:after {
   content: url(docx-icon.svg);
}
a[href$="odf"]:after {
   content: url(open-office-icon.svg);
}
Copy the code

You can also ensure that ICONS only appear on downloadable links by overlaying property selectors.

a[download][href$="pdf"]:after {
   content: url(pdf-icon.svg);
}
Copy the code

Overwrite or reuse obsolete/deprecated code

We’ve all come across old websites with outdated code, and before HTML5, you might need to override or even reapply styles implemented as attributes.

<div bgcolor="#000000" color="#FFFFFF">Old, holey genes</div> div[bgcolor="#000000"] { /*override*/ background-color: # 222222! important; } div[color="#FFFFFF"] { /*reapply*/ color: #FFFFFF; }Copy the code

Override specific inline styles

Sometimes you will encounter inline styles that affect the layout, but we haven’t changed them. So here’s one way to do it.

This works best if you specify the exact properties and values to override and want to override it wherever it appears.

For this example, the margins of the elements are set in pixels, but need to be expanded and set in EM so that the elements are properly resized when the user changes the default font size.

<div style="color: #222222; margin: 8px; background-color: #EFEFEF;" Teenage Mutant Ninja Myrtle</div> div[style*="margin: 8px"] { margin: 1em ! important; }Copy the code

Display file type

By default, the list of acceptable files for file input is not visible. In general, we use pseudo-elements to expose them:

<input type="file" accept="pdf,doc,docx">

[accept]:after {
   content: "Acceptable file types: " attr(accept);
}
Copy the code

HTML Accordion menu

The Details and Summary TAB is a way to do the extension/accordion menu using only HTML. Details includes the Summary TAB and what to display when the accordion opens. Clicking summary expands the Details TAB and adds the open property, which makes it easy to style the open Details TAB:

details[open] {
   background-color: hotpink;
}
Copy the code

The print link

Displaying urls in print styles put me on the path to understanding property selectors. You should now know how to build it yourself by selecting all the tags with href, adding the pseudo-elements, and then printing them with attr() and content.

a[href]:after {
   content: " (" attr(href) ") ";
}
Copy the code

Custom hints

Creating custom tooltips using property selectors is fun and easy:

[title] {
  position: relative;
  display: block;
}
[title]:hover:after {
  content: attr(title);
  color: hotpink;
  background-color: slateblue;
  display: block;
  padding: .225em .35em;
  position: absolute;
  right: -5px;
  bottom: -5px;
}
Copy the code

Access key

One of the great things about the Web is that it provides many different options for accessing information. One rarely used property is the ability to set an Accesskey so that the item can be accessed directly through the key combination and the letter set by the Accesskey (the exact key combination depends on the browser). But it’s not easy to figure out which keys are set on a site

The following code displays these keys: Focus. I don’t use mouse hover because most of the time the people who need accessKey are the ones who have trouble using the mouse. You can add it as a second option, but make sure it’s not the only one.

a[accesskey]:focus:after {
   content: " AccessKey: " attr(accesskey);
}
Copy the code

diagnosis

These options are used to help us identify problems locally during the build process or when trying to fix them. Placing this content on our production site will cause a user error.

Audio without controls property

I don’t use the Audio tag very often, but when I do, I often forget to include the Controls property. Result: Nothing is displayed. If you are in Firefox, this code can help you solve the problem if you hide the audio element, or if the syntax or some other problem prevents it from appearing (Firefox only) :

audio:not([controls]) {
  width: 100px;
  height: 20px;
  background-color: chartreuse;
  display: block;
}
Copy the code

There is noaltThe text

Images without Alt text are an accessibility nightmare. It’s hard to find them just by looking at the page, but if you add them, they pop up (Alt text is a better way to explain what the image is for when the page image fails to load) :

img:not([alt]) { /* no alt attribute */ 
  outline: 2em solid chartreuse; 
}
img[alt=""] { /* alt attribute is blank */ 
  outline: 2em solid cadetblue; 
}
Copy the code

Asynchronous Javascript file

A web page can be a collection of content management systems and plug-ins, frameworks and code, and determining which JavaScript loads asynchronously and which doesn’t can help you focus on improving page performance.

script[src]:not([async]) {
  display: block;
  width: 100%;
  height: 1em;
  background-color: red;
}
script:after {
  content: attr(src);
}
Copy the code

JavaScript event elements

You can highlight elements with JavaScript event attributes in order to refactor them into JavaScript files. I’ll focus on the OnMouseOver property here, but it applies to any JavaScript event property.

[OnMouseOver] {
   color: burlywood;
}
[OnMouseOver]:after {
   content: "JS: " attr(OnMouseOver);
}
Copy the code

Hide items

If you need to see where to hide elements or hide input, you can use them to display

[hidden], [type="hidden"] {
  display: block;
}
Copy the code

Your likes are my motivation to keep sharing good things.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.