Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Look at this article, css selector knowledge summary


May 04, 2021 CSS


Table of contents


The CSS selector is familiar to most technicians, for example, assuming that a class is added to a p-tag, but some of the properties in that class do not work after execution. A Firebug look reveals that properties that don't work are overwritten, and this time you suddenly realize the priority issue of the CSS selector. S trictly speaking, there are three types of selectors: label name selectors, class selectors, and ID selectors. T he so-called descendant selectors and group selectors are simply extended applications to the first three selectors. T he way in which style is written within a label should be a way of introducing CSS, not a selector, because the selector is not used at all. A nd the average person combines the above, so there are five or six selectors.


Look at this article, css selector knowledge summary


The most basic selectors are element selectors (such as div), ID selectors (such as #header) and class selectors (such as .tweets).

Some of the less common selectors include pseudo-class selectors (:hover), many complex CSS3 and regular selectors, such as: first-child, class, and "grid-". The CSS selector is highly inherited, and to quote Steve Souders, the CSS selector efficiency is sorted from highest to below:

Selector Usage
id selector #myid
Class selector .myclassname
Label selector div,h1,p
Adjacent selectors h1+p
Sub-selector ul > li
Descendant selector li a
Wildcard selector *
Property selector a[rel="external"]
Pseudo-class selector a:hover, li:nth-child



Even though the ID selector is fast and efficient, it's just that. From Steve Souders' CSS Test, we can see that the difference in speed between ID selectors and class selectors is small.

On Firefox 6 on Windows, I measured a simple class selector with a reflow figure redrawing speed of 10.9ms and an ID selector of 12.5ms, so in fact the ID is a little slower than the class selector redraw.

The difference in speed between ID selectors and class selectors is largely ireloidal.

The test of a label selector (a) shows that it is much slower than a class or ID selector. O n a test of a deeply nested descendant selector, the display data is about 440! From here we can see that the differences between the ID/class selectors and the element/descendant selectors are large, but the differences between them are small.


What is the priority of the selector?

In general, the more special the selector, the higher its priority. T hat is, the more accurate the selector points, the higher its priority. T ypically, we use 1 for the priority of the label name selector, 10 for the class selector, and 100 for the ID selector. F or example, in the example above, .polaris span s color:red; T he selector priority is 10 plus 1 is 11, while .polaris has a priority of 10, and the browser naturally displays the red word. With this in understanding, the following priority calculations are easy:

Div.test1 .SPAN VAR priority 1 + 10 +10 +1

SPAN # xxx .songs Li priority 1 + 100 + 10 + 1

#xxx li priority 100 + 1

For when to use which selectors, the principles for using different selectors are:
  1. Accurately select the label to control;
  2. Use the selector with the most reasonable priority;
  3. HTML and CSS code is as simple and beautiful as possible. Usually:

(1) The most common selectors are class selectors.

(2) li, td, dd, etc. often appear in large numbers of consecutive, and the same or similar style of labels, we use the class selector and label name selector combined with the descendant selector .xx li/td/dd .

(3) ID selectors are rarely used, and of course many front-end developers prefer header, footer, banner, and conntent to set up as ID selectors, because the same style cannot be a second time in a page.


Here you have to mention the way CSS is written using the introduction of CSS within the label, i.e.:

<div style="color:red">polaris</div>

The priority at this time is the highest. W e give it a priority of 1000, which is not recommended for new users. T his is also completely contrary to the idea of content and display separation. The benefits of DIV-CSS can no longer be reflected.

How can I improve CSS selector performance?

1. Avoid using universal selectors

.content  {color: red;}

After the browser matches all the elements in the document, it matches the element content up step by step, until the root node of the document. Therefore, the matching overhead is very large, so you should avoid using a key selector that is a pass-through selector.


2. Avoid using labels or class selectors to restrict id selectors

Avoid

button#backButton {…}

Avoid

.menu-left#newMenuIcon {…}

Recommended Use

#backButton {…}

Recommended Use

#newMenuIcon {…}

3, avoid using label restriction class selector

Avoid

treecell.indented {…}

Recommended Use

.treecell-indented {…}

Optimal use

.hierarchy-deep {…}

4, avoid the use of multi-layer label selectors. Use class selector replacement to reduce csss lookups

Avoid

treeitem[mailfolder="true"] > treerow > treecell {…}

Recommended Use

.treecell-mailfolder {…}

5, avoid the use of sub-selectors

Avoid

treehead treerow treecell {…}

BETTER, BUT STILL BAD

treehead > treerow > treecell {…}

Recommended Use

.treecell-header {…}

6, the use of inheritance

Avoid

#bookmarkMenuItem > .menu-left { list-style-image: url(blah) }

Recommended Use

#bookmarkMenuItem { list-style-image: url(blah) }


Simple and efficient CSS

The so-called efficient CSS is to let the browser look for style matching elements as little as possible, here are some of our common write CSS make some inefficient errors:


Look at this article, css selector knowledge summary


Do not use the label name in front of the ID selector

Generally written: DIV-divBox

Better writing: #divBox

Explanation: Because the ID selector is unique, adding div adds unnecessary matches.


Don't use the label name before the class selector

General writing: span.red

Better writing: .red

Explanation: Same as the first one, but if you define multiple .reds and are different styles under different elements, you can't remove them, as defined in your CSS file as follows:

p.red{color:red;}

span.red{color:#ff00ff}

If this definition is not to be removed, it will be confusing to remove, but it is recommended not to write this


Use hierarchical relationships as little as possible

General writing: #divBox p .red:color:red; }

Better writing: .red.


Use class instead of hierarchical relationships

General writing: #divBox ul li a'display:block; }

Better writing: .block (display: block; }


30 class CSS selectors that must be remembered

Presumably everyone knows the "id", "class" and "class" selectors, and you're using them all, so you're making the wrong choice with a greater level of flexibility. M ost of the selectors mentioned below are under the CSS3 standard, so they only work in the latest version of the browser, and you should keep them all in your smart head.

1.*

*{

margin: 0;

padding: 0;}

Before we look at the more advanced selectors, we should get to know this well-known empty selector. T he asterisk will select all the elements on the page. M any developers use it to empty margins and padding. O f course it's no problem for you to use this in practice, but I don't recommend using it in a production environment. I t adds a lot of unnecessary things to the browser. It can also be used to select all child elements of an element.

#container * {

border: 1px solid black;}

It selects #container elements under the list. Of course, I still don't recommend you to use it, if possible.

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

2. #X

#container {

width: 960px;

margin: auto;}

You can use id to locate an element in the selector. T hat's what people usually do, and then when you use it, you have to be pretty careful. I need to ask myself: Do I have to assign this element an id to locate it?

The id selector is very strict and you can't use it again. If possible, try using a label name, a new element in HTML5, or a pseudo-class.

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

3. .

.error {

color: red;}

This is a class selector. U nlike the id selector, it can locate multiple elements. Y ou can use class when you want to style multiple elements. When you're going to decorate a particular element, it's using id to locate it.

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

4. X Y

li a {

text-decoration: none;}

The next common use is the look-out selector. I f you want to be more specific about locating an element, you can use it. F or example, if you don't need to locate all the a elements, you just need to position the a label under the li label? That's when you need to use the selection selector.

Expert Tip: If your selector is like X Y Z A B.error, you're wrong. Always remind yourself if you really need to decorate so many elements.

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

5. X

a { color: red; }

ul { margin-left: 0; }

If you want to locate all the labels on the page, not through id or 'class', it's simple to use the type selector directly.

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

6. X:visited and X:link

a:link {color:red;}

a:visited {color: purple;}

We use: link, a pseudo-class, to locate all links that have not been visited.

In addition, we also use: visited to locate all links that have already been visited.

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

7. X+Y

ul + p {

color: red;}

This is called an adjacent selector. I t directs the selection of the direct successor element of the specified element. The example above is to select the first paragraph after all ul tags and set their colors to red.

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

8. X>Y

div#container > ul {

border: 1px solid black;}

The difference between X Y and X sgt; Y is that the next conductor selects its direct child elements. Take a look at the following example:

<div id="container">

<ul><li> List Item

<ul><li> Child </li>

</ul></li><li> List Item </li><li> List Item </li><li> List Item </li></ul>

</div>

#container only select all direct ul elements under div with id 'container' selected. It does not navigate to a ul element like the one under the first li.

For some reason, using a child node combination selector can have many performance benefits. In fact, this is highly recommended when using the css selector in javascript.

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

9. X ~ Y

ul ~ p {

color: red;}

The brother node combination selector is very similar to the X-Y, and then it's not that strict. T he ul-p selector selects only those elements that follow the specified element immediately. This selector selects all the matching elements that follow the target element.

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

10. X[title]

a[title] {

color: green;}

This is called a property selector, and in this example above, only elements with title properties are selected. A nchor labels that do not have this property will not be modified by this code. S o think about if you want to be more specific about screening? That...

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

11. X[href="foo"]

a[href="http://strongme.cn" rel="external nofollow" target="_blank" ] {

color: #1f6053; /* nettuts green */}

The above piece of code will set the anchor label with a href property value of http://strongme.cn to green, while the other labels will not be affected.

Note that we have enclosed values with double quotes.Then you have to use a double quotes when using JavaScript.If possible, try to use the standard CSS3 selector.

This can be used, but it's still a bit dead, if it's not this link, it's a similar link, then you have to use a regular expression.

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

12. X[href="strongme"]

a[href="strongme"] {

color: #1f6053;}

Tada, which is exactly what we need, strongme must appear in href of the anchor strongme.cn or strongme.com or www.strongme.cn be selected.
But remember that this is a very broad expression. If the anchor label does not point to strongme site, and if you want more specific $ use s and $ to represent the beginning and end of the string, respectively. ^

Compatibility

  • IE7+

  • Firefox

  • Chrome

  • Safari

  • Opera

13. X[href^="href"]

a[href^="http"] {

background: url(path/to/external/icon.png) no-repeat;

padding-left: 10px; }

You must have been curious, some sites next to the anchor label there will be an external chain icon, I also believe you have certainly seen this situation. T his design will make it clear that you will jump to another website.
It's easy to do with carat symbols. I t is typically used to identify the beginning in a regular expression. If we want to locate a label that starts http we can use code similar to the one above. href

Note that we http:// which is not necessary because it doesn't https://

What if we want to find all the anchor tags that point to a picture? Then let's use &

Compatibility

  • IE7+

  • Firefox

  • Chrome

  • Safari

  • Opera

14. X[href$=".jpg"]

a[href$=".jpg"] {

color: red; }

This time we used the regular expression $ represent the end of the string. T his code means searching for all the picture links, or other links .jpg the image. But remember that this writing doesn't gifs pngs

Compatibility

  • IE7+

  • Firefox

  • Chrome

  • Safari

  • Opera

15. X[data-*="foo"]

a[data-filetype="image"] {

color: red;}

Back in Article 8, how do we select all picture types png jpeg jpg gif W e can use multi-selectors. Here's a look:

a[href$=".jpg"],

a[href$=".jpeg"],

a[href$=".png"],

a[href$=".gif"] {

color: red; }

But it says it hurts, and it's inefficient. A nother approach is to use custom properties. W e can add a property data-filetype type of picture this link points to.
[html]
Image Link That with this hook, we can go to the standard way of selecting only the anchor image the file type image.

a[data-filetype="image"] {

color: red; }


Compatibility

  • IE7+

  • Firefox

  • Chrome

  • Safari

  • Opera

16. X[foo~="bar"]

a[data-info~="external"] {

color: red; }

a[data-info~="image"] {

border: 1px solid black; }

I think it's going to surprise your little buddy. F ew people know this technique. T his ~ locate labels where a property value is a space separating multiple values.
Continuing with the example in Article 15, we can set data-info that can be used to set any value that we need to be space-separated. In this example we will indicate that they are external connections and picture links.

Click Me, Fool

Once we've set this flag for these elements, we ~ to locate the labels.

/ Target data-info attr that contains the value "external" /

a[data-info~="external"] {

color: red;}

/ And which contain the value "image" /

a[data-info~="image"] {

border: 1px solid black;}

## 17. X:checked

input[type=radio]:checked {

border: 1px solid black; }

The pseudo-class writing above can locate the checked single and multi-box, and that's it.

Compatibility

  • IE9+

  • Firefox

  • Chrome

  • Safari

  • Opera

18. X:after

before and after these two pseudo-classes. I t seems that every day everyone can find creative ways to use them. T hey generate something around the selected label.
Many properties are used inside for the first time when using the .clear-fix technique.

.clearfix:after {

content: "";

display: block;

clear: both;

visibility: hidden;

font-size: 0;

height: 0;

}

.clearfix {

display: inline-block;

_height: 1%;

}

The above code fills in a blank after the target label and clears it. Y ou must put it in your treasure pot in this way. T his is overflow:hidden method is not working.

According to the CSS3 standard, two colons can be :: . T hen, for compatibility, the browser also accepts a double quote. In fact, in this case, it is wise to use a colon.

Compatibility

  • IE8+

  • Firefox

  • Chrome

  • Safari

  • Opera

19. X:hover

div:hover {

background: #e3e3e3; }

Needless to say, everyone must know it. T he official saying user action pseudo class It sounds a little confusing, but it's okay. If you want to paint some color in a place where the user's mouse floats, this pseudo-class writing can be done.

Note that older versions of IE only work for a pseudo-class :hover the anchor a label.

It is usually used when the mouse floats over the anchor link and the border is added.

a:hover {

border-bottom: 1px solid black;

}

Expert Tip: border-bottom:1px solid black t han text-decoration:underline I t's going to look a lot better.

Compatibility

  • IE6 plus (IE6 only works on anchor labels)

  • Firefox

  • Chrome

  • Safari

  • Opera

20. X:not(selector)

div:not(#container) {

color: blue;

}

取反 to take anti-pseudo classes, assuming that we select all div tags div id for container Then the code above can do it.

Or I want to select all labels except all out of the paragraph label.

:not(p) {

color: green;

}

Compatibility

  • IE9+

  • Firefox

  • Chrome

  • Safari

  • Opera

21. X::pseudoElement

p : : first-line {

font-weight: bold;

font-size:1.2em;

}

We can :: to select parts of a label, such as the first paragraph, or the first word without. But remember that you have to use a block label to work.

Pseudo-labels are made up of :: : .

Position the first word

p::first-letter {

float: left;

font-size: 2em;

font-weight: bold;

font-family: cursive;

padding-right: 2px;

}

The above code finds all the paragraphs on the page and specifies the first word of each paragraph.

It is usually used in some news and newspapers where the focus is on the content.

Position the first line of a segment

p::first-line {

font-weight: bold;

font-size: 1.2em;

}

Similar ::first-line the first line of the paragraph is selected.

For compatibility, older browsers were also compatible with single colon writing, :first-line :first-letter :before :after But this compatibility does not work for the newly introduced features.

Compatibility

  • IE6+

  • Firefox

  • Chrome

  • Safari

  • Opera

22. X:nth-child(n)

li:nth-child(3) {

color: red;

}

Remember when we were faced with how to get the first few elements of the push-down label that there was nowhere to go, and the days of nth-child are gone forever.

Note nth-child accepts a shaping parameter, and then it does not start at 0. If you want to get the second element then the value li:nth-child(2) .

We can even get several sub-labels defined by the variable name. For example, li:nth-child(4n) to get labels every 3 elements.

Compatibility

  • IE9+

  • Firefox3.5+

  • Chrome

  • Safari

23. X:nth-last-child(n)

li:nth-last-child(2) {

color: red;

}

Suppose you have more N elements in a ul tag, and you only want to get the last three li:nth-child(397) can replace it with nth-last-child

This technique can be completely correct in place of the 16th TIP, the difference is that it starts at the end and goes back.

Compatibility

  • IE9+

  • Firefox3.5+

  • Chrome

  • Safari

  • Opera

24. X:nth-of-type(n)

ul:nth-of-type(3) {

border: 1px solid black;

}

Once upon a time, we didn't want to select child nodes, we wanted to choose based on the type of element.

Imagine having five ul If you only want to decorate the third of them, id property, you can do it nth-of-type(n) and ul be bordered.

Compatibility

  • IE9+

  • Firefox3.5+

  • Chrome

  • Safari

25. X:nth-last-of-type(n)

ul:nth-last-of-type(3) {

border: 1px solid black;

}

Similarly, you can nth-last-of-type to get labels in reverse order.

Compatibility

  • IE9+

  • Firefox3.5+

  • Chrome

  • Safari

  • Opera

26. X:first-child

ul li:first-child {

border-top: none;

}

This structural pseudo-class can be selected to the first sublabel, which you will often use to remove the first and last borders.

Assuming there's a list, each label has an upper and lower border, the effect is that the first and last one will look a little strange. This is when you can use this pseudo-class to handle this situation.

Compatibility

  • IE7+

  • Firefox

  • Chrome

  • Safari

  • Opera

27. X:last-child

ul > li:last-child {

color: green;

}

In first-child last-child is the last label of the parent label.

For example
Label

List Item

List Item

List Item

There's nothing here, it's a List.

ul {

width: 200px;

background: #292929;

color: white;

list-style: none;

padding-left: 0;

}

li {

padding: 10px;

border-bottom: 1px solid black;

border-top: 1px solid #3c3c3c;

}

The code above sets the background color, removes the browser's default margin, li border for each li to highlight a certain depth.

Look at this article, css selector knowledge summary

Compatibility

  • IE9+

  • Firefox

  • Chrome

  • Safari

  • Opera

28. X:only-child

div p:only-child {

color: red;

}

To tell you the truth, you'll find that you hardly use this pseudo-class. However, it is available and will need it.

It allows you to get parent tags that have only one child tag. Like the code above, only the div of a div is colored.

My paragraph here.

Two paragraphs total.

Two paragraphs total.

In the example above, the second div not selected. Once the first div has div sub-paragraphs, this no longer works.

Compatibility

  • IE9+

  • Firefox

  • Chrome

  • Safari

  • Opera

29. X:only-of-type

li:only-of-type {

font-weight: bold;

}

Structural pseudo-classes can be used very smartly. I t locates the target of a label that has only one sub-label. Imagine you want to get a ul tag with only ul

Using ul li selects all li That's when only-of-type

ul > li:only-of-type {

font-weight: bold;

}

Compatibility

  • IE9+

  • Firefox 3.5+

  • Chrome

  • Safari

  • Opera


30. X:first-of-type first-of-type

Pseudo classes can select the first brother label that specifies a label.

Test

My paragraph here.

List Item 1

List Item 2

List Item 3

List Item 4

Come and you take list Item 2 out, and if you've already taken it out or given up, go ahead.

Solution 1
There are many ways, we look at some more convenient. The first first-of-type

ul:first-of-type > li:nth-child(2) {

font-weight: bold;

}

Find the first ul label, then the direct li and then the second child node.
Solution 2
Another solution is proximity to selectors.

p + ul li:last-child {

font-weight: bold;

}

In this case, find the direct ul label under p and then find its last direct sub-label.

Solution 3
We can play with these selectors at will. Let's take a look at:

ul:first-of-type li:nth-last-child(1) {

font-weight: bold;

}

Get the first ul label on ul page first, and then find the last sublabel.

Compatibility

  • IE9+

  • Firefox 3.5+

  • Chrome

  • Safari

  • Opera

Conclusion

If you want to compromise with older browsers, such as IE6, you'll have to be careful when using these new selectors. B ut don't let IE6 stop you from learning these new skills. T hen you're cruel to yourself. Remember to check the compatibility list more, or use Dean Edward's excellent IE9 .js script to get your browser to have these features.

Second, when using jQuery, try to use the native CSS3 selector. M aybe live to keep your code running fast. This allows the selector engine to use the browser native parser instead of the selector itself.