To improve the front-end layout capabilities, these CSS properties need to be learned!

Front end intelligence 2020-11-13 08:10:20
improve front-end end layout capabilities

author :John
translator : The front end little wisdom
source :smashingmagazine
Enjoy it , Develop habits

this paper GitHub I have included , More categories of previous high praise articles , I've also compiled a lot of my documents , And tutorial materials . welcome Star And perfection , You can refer to the interview site review , I hope we have something .

Recently, we open source a Vue Components , It's not perfect , Welcome to improve it together , I hope you can give me a star support , Thank you .

github Address :

Property selectors are amazing . They can help you get rid of tough problems , Help you avoid adding classes , And point out some problems in the code . But don't worry , Although property selectors are very complex and powerful , But they are easy to learn and use . In this paper , We'll talk about how they work , And give some ideas on how to use them .

Will usually HTML Attribute in square brackets , It's called a property selector , as follows :

[href] {
color: red;

So anything with href The text color of elements with no more specific selectors will be Red . Property selectors have the same properties as classes .

notes : More about cage matching CSS Specificity , You can read CSS characteristic : What you should know , Or if you like Star Wars :CSS Character Wars .

But you can do more with property selectors . It's like yours DNA equally , They have internal logic to help you choose a variety of attribute combinations and values . They can match any of the attributes , Even string values , Not like labels 、 Class or id Selectors match exactly like that .

Attribute selector

Property selectors can exist independently , More specifically , If you need to choose all with title Attribute div label , You can do that :


But you can also choose to have title Attribute div Child elements

div [title]

It should be noted that , There is no space between them, which means that the attributes are on the same element ( It's like there's no space between elements and classes ), And the space between them means the descendant selector , That is, select the child element of the element with the attribute .

You can select properties with specific attribute values more finely .


All of the above have exact names dna Of div, Although there are selector algorithms that can handle every situation ( And more ), But there's no choice here “dna is awesome” or “dnamutation” The title of the .

Be careful : in the majority of cases , No quotation marks are required in the property selector , But I use them , Because I believe it can improve the readability of HD code , And make sure that the boundary use cases work properly .

If you want to choose title contain dna The elements of , Such as “my beautiful dna” perhaps “mutating dna is fun!” , have access to The waves, (~).


If you want to match with dna At the end of the title, Such as “dontblamemeblamemydna” or “his-stupidity-is-from-upbringing-not-dna” , Just ready to use $ identifier :


If you want to match with dna At the beginning title, Such as “dnamutants” or “dna-splicing-for-all” , Just ready to use ^ identifier :


Although exact matching can help , But it may choose to be too tight , also ^ Symbol matching may be too wide for your needs . for example , Maybe you don't want to choose “genealogy” The title of the , But still choose “gene” and “gene-data”. Pipeline features (|) this is it , Property must be complete and only 's words , Or with - Separate .


Last , There is also a fuzzy search attribute operator that matches any substring , Attribute to do string splitting , As long as it can be disassembled dna This word will do :


What makes these property selectors even more powerful is , They are stackable , Allows you to select elements with multiple matching factors .

If you need to find one a label , It has one title , And there's one with “genes” At the end of the class, You can use the following methods :


You can not only choose HTML Attribute of element , 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>
.joke:hover:after {
content: "Answer:" attr(title);
display: block;

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

The last thing to know is , You can add a logo , Make property search case insensitive . Add before closing bracket i

[title*="DNA" i]

So it matches dna, DNA, dnA etc. .

Now we've seen how to use the property selector to select , Let's look at some use cases . I divide them into two categories : General purpose and The diagnosis .

General purpose

Input type style settings

You can use different styles for input types , E-mail and phone calls .

input[type="email"] {
color: papayawhip;
input[type="tel"] {
color: thistle;

Show phone links

You can hide specific size phone numbers and show phone links , So that you can easily make a call on your mobile phone . {
display: none;
a[href^="tel"] {
display: block;

internal link vs External links , Secure links vs Unsafe Links

You can differentiate between internal and external links , And set the secure link to be different from the unsafe link :

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);

Download Icon

HTML5 One attribute given to us is “ download ”, It tells the browser , You guessed it , Download the file instead of trying to open it . This is for things that you want people to visit but don't want them to open immediately PDF and DOC Very useful . It also makes it easier to download a large number of files in a row . The disadvantage 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 things like this :

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

You can also use different icons ( Such as PDF And DOCX And ODF etc. ) To represent the file type , wait .

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);

You can also overlay the property selector to make sure that the icons only appear on downloadable Links .

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

To cover or reuse abandoned / Abandoned code

We all come across outdated code, old websites , stay HTML5 Before , You may 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;

Override specific inline styles

Sometimes you come across some inline styles , These styles affect the layout , But we didn't change the styles . So here's one way .

If you want to override the exact properties and values , And it's everywhere it wants to be covered , Then this method works best .

For this example , The margin of the element is set in pixels , But need to be in em To expand and set , So that the elements can be adjusted correctly 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;

Show file type

By default , The input file is not visible . Usually , We use pseudo elements to expose them :

<input type="file" accept="pdf,doc,docx">
[accept]:after {
content: "Acceptable file types: " attr(accept);

html Accordion menu

details and summary Label is a kind of use only HTML Expand / Accordion menu method ,details It includes summary What to show when the label and accordion are opened . Click on summary It will unfold details Tag and add open attribute , We can go through open Properties are easily opened for details Label setting style :

details[open] {
background-color: hotpink;

Print Links

Show in print style URL It took me on the road to understanding property selectors . You should now know how to build it yourself , You just have to choose to carry href All tags for , Add pseudo elements , And then use attr() and content Print them .

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

Custom prompt

Using property selectors to create custom tooltips 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;

Easy key

web One of the advantages of is that it provides many different information access options . One rarely used property is to set accesskey The ability of , So you can use key combinations and accesskey Set the letters to access the project directly ( The exact key combination depends on the browser ). But it's not easy to know which keys are set on a website

The following code shows these keys :focus. I don't use the mouse to hover , Because most of the time you need to accesskey People who have trouble using the mouse . You can add it as a second option , But make sure it's not the only option .

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

The diagnosis

These options are used to help us identify the problem locally during the build process or when trying to fix the problem . Putting this content on our production website can cause users to make mistakes .

No, controls Attribute audio

I don't use it very often audio label , But when I use it , I often forget to include controls attribute . result : Nothing is displayed . If you are in the Firefox, If you hide audio elements , Or grammar or some other problem that prevents it from happening ( Only applicable to Firefox), This code can help you solve the problem :

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

No, alt Text

No, alt Images of text are an accessibility nightmare . It's hard to find them just by looking at the page , But if you add them , They'll pop out ( When the page image fails to load ,alt Text can better explain the role of pictures ):

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

asynchronous Javascript file

Web pages can be content management systems and plug-ins , A collection of frameworks and code , Determine what JavaScript Asynchronous loading and what doesn't load 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);

JavaScript Event elements

You can highlight having JavaScript The element of the event attribute , In order to refactor them to JavaScript In file . I'm going to focus here OnMouseOver attribute , But it applies to anything JavaScript Event properties .

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

Hidden item

If you need to see the location of hidden elements or hidden inputs , You can use them to show

[hidden], [type="hidden"] {
display: block;

original text :https://www.smashingmagazine....

Possible after code deployment BUG There's no way to know in real time , In order to solve these problems afterwards BUG, It took a lot of time log debugging , This way, I'd like to recommend an easy-to-use one for you BUG Monitoring tools Fundebug.


Articles are updated every week , You can search by wechat 「 The big move the world 」 First time reading and urging ( One or two articles earlier than blog ), this paper GitHub Included , I organized a lot of my documents , welcome Star And perfection , You can refer to the interview site review , Pay attention to official account. , The background to reply welfare , You can see the benefits , You'll see .

本文为[Front end intelligence]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple