Table of Contents
Attribute selector
General purpose
Settings for input type styles
Show phone link
内部链接 vs 外部链接,安全链接 vs 非安全链接
下载图标
覆盖或重新使用已废弃/弃用的代码
重写特定的内联样式
显示文件类型
html 手风琴菜单
打印链接
自定义提示
便捷键
诊断
没有 controls 属性的 audio
没有 alt 文本
异步 Javascript 文件
JavaScript 事件元素
隐藏项
Home Web Front-end CSS Tutorial Learn about some CSS attribute selectors that improve front-end development efficiency

Learn about some CSS attribute selectors that improve front-end development efficiency

Oct 20, 2020 pm 05:34 PM
css attribute selector

Learn about some CSS attribute selectors that improve front-end development efficiency

(Recommended tutorial: CSS Tutorial)

Attribute selectors are amazing. They can get you out of sticky situations, help you avoid adding classes, and point out problems in your code. But don't worry, although attribute 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.

Usually put HTML attributes in square brackets, called attribute selectors, as follows:

[href] {
   color: red;
}
Copy after login

In this way, any attribute with href and The text color of elements without a more specific selector will be red. Attribute selectors have the same properties as classes.

NOTE: For more on the CSS specificity of cage matching, you can read CSS Properties: Things You Should Know or if you like Star Wars: CSS Properties Wars.

But you can do more with attribute selectors. Like your DNA, they have internal logic to help you choose various attribute combinations and values. They can match any attribute within an attribute, even a string value, rather than an exact match like tag, class, or id selectors.

Attribute selector

The attribute selector can exist independently. More specifically, if you need to select all p tags with the title attribute, you can do this:

p[title]
Copy after login

But you can also select the child elements of p with the title attribute through the following operations

p [title]
Copy after login

It should be noted that there is no space between them means that the attribute is on the same element (like there is no space between the element and the class), and the space between them means that the descendant selector, i.e. selects the child elements of the element with that attribute.

You can more granularly select attributes with specific attribute values.

p[title="dna"]
Copy after login

The above selects all p's with the exact name dna, although there are selector algorithms to handle every case (and more), "dna" will not be selected here is awesome" or "dnamutation" 's title.

Note: In most cases, quotes are not required in attribute selectors, but I use them because I believe it improves code readability and ensures that edge use cases will work correctly.

If you want to select title elements containing dna, such as "my beautiful dna" or "mutating dna is fun!", you can use the tilde (~).

p[title~="dna"]
Copy after login

If you want to match title ending with dna, such as "dontblamemeblamemydna" or "his-stupidity-is-from-upbringing-not-dna", Just use the $ identifier:

[title$="dna"]
Copy after login

if you want to match title starting with dna, such as "dnamutants" or "dna- splicing-for-all", just use the ^ identifier:

[title^="dna"]
Copy after login

While exact matching is helpful, it may be too tight, and ^ Symbol matching may be too broad for your needs. For example, you may not want to select the title "genealogy" but still select "gene" and "gene-data". Pipe Characteristics (|) That's it, the attribute must be a complete and unique word, or separated by -.

[title|="gene"]
Copy after login

Finally, there is a fuzzy search attribute operator that matches any substring. String splitting is done in the attribute, as long as the word dna can be separated:

[title*="dna"]
Copy after login

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 a a tag that has a title and a class ending with "genes", you can use the following method:

a[title][class$="genes"]
Copy after login

Not only can you select attributes of 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 after login
.joke:hover:after {
   content: "Answer:" attr(title);
   display: block;
}
Copy after login

The above code will display a custom string when the mouse is hovered.

The last thing to know is that you can add a flag to make attribute searches case-insensitive. Add i before the closing square bracket:

[title*="DNA" i]
Copy after login

so it will match dna, DNA, dnA, etc.

Now that we have seen how to make selections using attribute selectors, let's look at some use cases. I divide them into two categories: General purpose and Diagnostic.

General purpose

Settings for input type styles

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

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

You can hide phone numbers in specific sizes and show phone link to make calls easily on your phone.

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

内部链接 vs 外部链接,安全链接 vs 非安全链接

你可以区别对待内部和外部链接,并将安全链接设置为与不安全链接不同:

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 after login

下载图标

HTML5 给我们的一个属性是“下载”,它告诉浏览器,你猜对了,下载该文件而不是试图打开它。这对于你希望人们访问但不希望它们立即打开的 PDFDOC 非常有用。它还使得连续下载大量文件的工作流程更加容易。下载属性的缺点是没有默认的视觉效果将其与更传统的链接区分开来。通常这是你想要的,但如果不是,你可以做类似下面的事情:

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

还可以使用不同的图标(如PDF与DOCX与ODF等)来表示文件类型,等等。

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 after login

你还可以通过叠加属性选择器来确保这些图标只出现在可下载链接上。

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

覆盖或重新使用已废弃/弃用的代码

我们都遇到过时代码过时的旧网站,在 HTML5 之前,你可能需要覆盖甚至重新应用作为属性实现的样式。

<p bgcolor="#000000" color="#FFFFFF">Old, holey genes</p>

p[bgcolor="#000000"] { /*override*/
   background-color: #222222 !important;
}
p[color="#FFFFFF"] { /*reapply*/
   color: #FFFFFF;
}
Copy after login

重写特定的内联样式

有时候你会遇到一些内联样式,这些样式会影响布局,但这些内联样式我们又没修改。那么以下是一种方法。

如果你道要覆盖的确切属性和值,并且希望在它出现的任何地方覆盖它,那么这种方法的效果最好。

对于此示例,元素的边距以像素为单位设置,但需要在 em 中进行扩展和设置,以便在用户更改默认字体大小时可以正确地重新调整元素。

<p style="color: #222222; margin: 8px; background-color: #EFEFEF;"Teenage Mutant Ninja Myrtle</p>

p[style*="margin: 8px"] {
   margin: 1em !important;
}
Copy after login

显示文件类型

默认情况下,文件输入的可接受文件列表是不可见的。 通常,我们使用伪元素来暴露它们:

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

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

html 手风琴菜单

detailssummary标签是一种只用HTML做扩展/手风琴菜单的方法,details 包括了summary标签和手风琴打开时要展示的内容。点击summary会展开details标签并添加open属性,我们可以通过open属性轻松地为打开的details标签设置样式:

details[open] {
   background-color: hotpink;
}
Copy after login

打印链接

在打印样式中显示URL使我走上了理解属性选择器的道路。 你现在应该知道如何自己构建它, 你只需选择带有href的所有标签,添加伪元素,然后使用attr()content打印它们。

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

自定义提示

使用属性选择器创建自定义工具提示既有趣又简单:

[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 after login

便捷键

web 的一大优点是它提供了许多不同的信息访问选项。一个很少使用的属性是设置accesskey的能力,这样就可以通过键组合和accesskey设置的字母直接访问该项目(确切的键组合取决于浏览器)。但是要想知道网站上设置了哪些键并不是件容易的事

下面的代码将显示这些键:focus。我不使用鼠标悬停,因为大多数时候需要accesskey的人是那些使用鼠标有困难的人。你可以将其添加为第二个选项,但要确保它不是惟一的选项。

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

诊断

这些选项用于帮助我们在构建过程中或在尝试修复问题时在本地识别问题。将这些内容放在我们的生产网站上会使用户产生错误。

没有 controls 属性的 audio

我不经常使用audio标签,但是当我使用它时,我经常忘记包含controls属性。 结果:没有显示任何内容。 如果你在 Firefox,如果隐藏了音频元素,或者语法或其他一些问题阻止它出现(仅适用于Firefox),此代码可以帮助你解决问题:

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

没有 alt 文本

没有 alt 文本的图像是可访问性的噩梦。只需查看页面就很难找到它们,但如果添加它们,它们就会弹出来(当页面图片加载失败时,alt文字可以更好的解释图片的作用):

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

异步 Javascript 文件

网页可以是内容管理系统和插件,框架和代码的集合,确定哪些JavaScript异步加载以及哪些不加载可以帮助你专注于提高页面性能。

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

JavaScript 事件元素

你可以突出显示具有JavaScript事件属性的元素,以便将它们重构到JavaScript文件中。这里我主要关注OnMouseOver属性,但是它适用于任何JavaScript事件属性。

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

隐藏项

如果需要查看隐藏元素或隐藏输入的位置,可以使用它们来显示

[hidden], [type="hidden"] {
  display: block;
}
Copy after login

原文地址:https://www.smashingmagazine.com/2018/10/attribute-selectors-splicing-html-dna-css/

The above is the detailed content of Learn about some CSS attribute selectors that improve front-end development efficiency. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

How to view the date of bootstrap How to view the date of bootstrap Apr 07, 2025 pm 03:03 PM

Answer: You can use the date picker component of Bootstrap to view dates in the page. Steps: Introduce the Bootstrap framework. Create a date selector input box in HTML. Bootstrap will automatically add styles to the selector. Use JavaScript to get the selected date.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

See all articles