CSS selectors

Regular structure


Every CSS rule has two basic parts: a selector and a declarative block



Element selector

Type selector

The most common selector is the HTML element (type) selector.

div {  
    color: blue;  
}
Copy the code

Selector grouping

We can use selectors when we want to group multiple elements in the same style.

div.span {  
    color: blue;  
} 
Copy the code

Rule: Place div and SPAN selectors to the left of the rule, and use a comma to separate the contents of the declaration block to apply to elements referenced by the previous two selectors.

Declare groups & groups

If there are multiple declaration blocks for the same selector, we can group the declaration. As follows:

div {  
    color: blue;  
}  
 
div {
	margin: 10px;
}
Copy the code

div {  
    color: blue;  
    margin: 10px;
} 
Copy the code


Wildcard selector

Css2 introduces a new simple selector, the wildcard selector. This selector can be matched with any element. It’s a grouping selector with all elements grouped together.

* {  
    color: blue;  
}  
Copy the code


Class selectors

The most common way to apply styles regardless of specific elements is to use class selectors. Before using the selector, you need to add the class attribute to the document element.

Rule: Class names are preceded by a dot (.) And can be combined with simple selectors (element selectors or wildcard selectors). The following example div.title limits the scope of the selector to “the div tag whose Class attribute contains title.” .main is equivalent to the wildcard selector (*.main).

.main {
	color: blue;
}
 
div.title {
	background: yellow;
}
Copy the code


Multiclass selectors

The order of class names is unlimited, separated by Spaces. If we want to set a div that also has the main Title class property to a unique bold font for the property value. Can be as follows:

div.main.title {
	font-weight: bold;
}
Copy the code

The ID selector

ID selectors are similar to class selectors, with some differences. ID selectors are preceded by a # (checkerboard number) instead of a dot (this can also be combined with wildcard or element selectors).

#main-content {
	color: blue;
}

div#main-content {
	color: blue;
}
 
*#main-content {
	color: blue;
}
Copy the code

Class selector and ID selector?

  1. Classes can be assigned to any number of elements, and ids are used only once in an HTML document. So if you have an element with an ID of main-content, no other element in the document can have an ID of main-content.
  2. Unlike class selectors, ID selectors cannot be used in combination because the ID attribute does not allow a blank delimited list of words.
  3. Another difference between class and ID names is that ID carries a higher weight when deciding which style to apply to an element.

extension

  1. In practice, browsers don’t always check for ID uniqueness in HTML. If you set the same ID attribute value for multiple elements, they may all be set to the same style. This is not the correct implementation, but it is common. The presence of multiple elements with the same ID value in a document can also cause DOM scripting problems because functions like getElementById() rely on the presence of only one element with a specific ID value in the document.
  2. Also note that classes and ids can be case-sensitive, depending on the language of the document. The HTML and XHTML languages define classes and ids as case-sensitive, so class and ID selectors need to match the case in the document.

Property selector

The class and ID selectors are actually selecting the value of the property. Because class and ID are attributes.

Classification:

  • Simple property selector
  • Exact attribute value selector
  • Partial match property selector
  • Header value property selector

Simple property selector

/* Select all div elements with class attributes */
div[class] {
	color: blue;
}
 
/* Select all elements with class attributes */
*[class] {
	color: blue;
}
 
/* Select the element whose class attribute contains main and has the title attribute */
.main[title] {
	color: blue;
}
 
/* Select the element with the title attribute and also the href attribute */
*[title][href] {
	color: blue;
}
Copy the code


Attribute value matching selector

On the basis of the attribute selector, you can further narrow the selector range to select those elements whose attribute is a certain value.


div[class="main title"] {
	color: blue;
}
 
<div class="main title">  
    Test css rel.  
</div>  
Copy the code

Some attribute values match

If the property accepts a list of words separated by Spaces, you can select a word match from one of them. The classic example is the class attribute. To use the above example: If you use an attribute selector to achieve partial attribute value matching, you need the following:

div[title~="main"] {
	color: blue;
}

<div title="main title">  
    Test css rel.  
</div> 
Copy the code

~: This symbol is the matching effect of the boundary. See the string matching property selector below



[Foo ~ = “bar”] : boundary

div[title~="main"] {
  color: blue;
}
Copy the code
<! - matching - >
<div title="1 main title">  
	Test css rel.  
</div> 

<! -- no match -->
<div title="1main title">  
	Test css rel.  
</div> 
Copy the code

[Foo * = “bar”] : substring

div[title*="main"] {
  color: blue;
}
Copy the code
<! - matching - >
<div title="1 main title">  
	Test css rel.  
</div> 

<! - matching - >
<div title="1main title">  
	Test css rel.  
</div> 
Copy the code

[Foo ^ = “bar”] : at the beginning

div[title^="main"] {
  color: blue;
}
Copy the code
<! -- no match -->
<div title="1 main title">  
	Test css rel.  
</div> 

<! - matching - >
<div title="main title">  
	Test css rel.  
</div> 
Copy the code

[Foo $= “bar”] : the end

div[title$="main"] {
  color: blue;
}
Copy the code
<! -- no match -->
<div title="1 main title">  
	Test css rel.  
</div> 

<! - matching - >
<div title="main"> 
	Test css rel.  
</div> 
Copy the code

[Foo | = “bar”] : begin with the bar for and use connector “-” split string.

div[title$="main"] {
  color: blue;
}
Copy the code
<! -- no match -->
<div title="1-main-title">  
  Test css rel.  
</div> 

<! - matching - >
<div title="main-title">  
  Test css rel.  
</div>

<! - matching - >
<div title="main">  
  Test css rel.  
</div>
Copy the code

Extension: Ignore case identifiers

Anyone who knows regular expressions knows what qualifier I means: To perform case-insensitive matches.

CSS Selectors Level 4 introduces case-insensitive options for attribute Selectors. Using I before the brackets close allows the selector to match an attribute value without case, ignoring the rules of the document language.

div[title~="Main" i] {
	color: blue;
}
Copy the code

As you can see from the red box in the figure, main currently performs case-insensitive matching. * As of the end of 2017, Opera Mini, Android browser and Edge won’t support this capability.

Relational selector

The power of CSS lies in the way it uses document structure to determine style and how styles apply to elements. Structure does play a very important role in how styles act on documents.

Descendant selector

Explanation: The Spaces between selectors are an example of a combinator. Each space combinator can be translated as “in… It is… Be a part of… Descendants “, provided the selector reads from right to left. Thus, h1 em can be translated as “apply the style to any EM element if it is a descendant of the H1 element.” (If the selector reads from left to right: “Select any H1, and if it contains an EM element, the rule will apply to the EM it contains”).

h1 em {color: gray; }Copy the code

Child element selector

The scope of the selection element is in the child element. You can use a child element selector, which is a curly brace (>).

h1 > strong {color: red; }Copy the code

Select adjacent sibling selectors

Selects the element immediately after another element that has the same parent element. The adjacent sibling selector uses the additive (+), the adjacent sibling combinator

li:nth-child(2) + li {  
  font-weight:bold;  
} 
Copy the code
<ul>  
    <li>List item 1</li>  
    <li>List item 2</li>  
    <li>List item 3</li>  
</ul>
Copy the code


The above code acts on the adjacent siblings of the second Li element. It’s the third element, Li.

Sibling selector

Unlike adjacent selectors, sibling selectors hit all sibling elements that meet the criteria, not the neighboring element. Use the symbol (~)

div ~ p {  
    font-weight:bold;  
}
Copy the code

Pseudo class selector

Pseudoclass selectors are interesting. They are ghost classes that act on changes in element state. Pseudo-class selectors can select elements and add styles based on the state of some deterministic element, the markup pattern in the document, or even the state of the document itself.

Link pseudo class

CSS2.1 defines two pseudo-classes for hyperlinks.

  • : linLK sets the style of hyperlink A before it is accessed.
  • :visited Sets the style of hyperlink A when its link address has been visited.

The four states of hyperlinks require the following writing order to take effect. The other two are dynamic pseudo-classes


a:link {  
    color: #FF0000; /* Unvisited links */  
    }         
a:visited {  
    color: #00FF00; /* Already visited links */  
    }     
a:hover {  
    color: #FF00FF; /* Mouse over the link */  
    }     
a:active {  
    color: #0000FF; /* Selected link */   
}  
Copy the code

Dynamic pseudo class

CSS2.1 defines three dynamic pseudo-classes that change the appearance of a document based on user behavior. These dynamic pseudo-classes used to always style hyperlinks with classes. But now dynamic pseudo-classes can be applied to any element, which is very important.

  • :hover sets the style of the element when it hovers.
  • :focus Sets the style of the object when it becomes the input focus (the object’s onfocus event occurs).
  • :active Sets the style of the element when activated by the user (the event that occurs between mouse click and release).
<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            h1 {
                font-size: 16px;
            }
 
            ul {
                list-style: none;
                margin: 0;
                padding: 0;
            }
 
            input:focus {
                background: #f6f6f6;
            }
 
            input:hover {
                background: blue;
            }
 
            input:active {
                background: red;
            }
        </style>
    </head>
    <body>
        <h1>Focus on the following input box</h1>
        <form action="#">
            <ul>
                <li><input value="Name" /></li>
                <li><input value="Unit" /></li>
                <li><input value="Age" /></li>
                <li><input value="Professional" /></li>
            </ul>
        </form>
    </body>
</html>
Copy the code





Structural pseudoclass

Most pseudo-classes are structural, in the sense that they are related to the markup structure of the document.

Select the first child element

**:first-child ** matches the first child E of the parent element. For this attribute to work, the E element must be a child of an element, with the highest parent of E being body, that is, E can be a child of body

<ul>
	<li> List item one </li>
	<li> List item two </li>
	<li> List item three </li>
	<li> List item four </li>
</ul>
Copy the code

Other pseudo-classes of Child

  • E:last-child {sRules} matches E, the last child of the parent element.
  • E:only-child {sRules} matches the only child E of the parent element.
  • E:nth-child(n) {sRules} matches the NTH child E of the parent element, assuming that the child is not E, then the selector is invalid.
  • E: nth-last-Child (n) {sRules} matches the penultimate child E of the parent element, assuming that the child is not E, then the selector is invalid.

Match the language

**:lang(fr) matches elements that use a special language.

<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            p:lang(zh-cmn-Hans) {
                color: #f00;
            }
            p:lang(en) {
                color: # 090;
            }
        </style>
    </head>
    <body>
        <p lang="zh-cmn-Hans">Test text in large chunks</p>
        <p lang="en">english</p>
    </body>
</html>
Copy the code

Selecting the root element

:root This is the essence of structural simplicity: pseudo-class selector :root selects the root element of the document. In HTML, the root element is always the HTML element.

:root {border: 10pxdotted gray; }Copy the code

Select the empty element

Using the pseudo-empty class, you can select any element that has no child nodes — no child elements of any type: no text nodes, no text and no whitespace.

<p></p>
<p> </p>
<p>
</p>
<p><! -- - a comment -- -- ></p>
Copy the code

The second and third paragraphs will not match :empty because they are not empty: they each contain a space and a newline character, and are treated as text nodes and therefore not empty. The last paragraph matches because comments are neither considered content nor white space. But if you add a space or a newline to either side of the comment, P: Empty will no longer match it.

Select all elements that are not elements

:not(s) Matches the element E that does not contain the s selector.

.demo li:not(:last-child) {
	border-bottom: 1px solid #ddd;
}
Copy the code

Adds a bottom edge to all list items except the last one in the list

Select the first element of a specific type

E:first-of-type {sRules} matches the first sibling element E of the same type. For this property to work, the element E must be a child of an element whose parent is at most HTML, that is, E can be a child of HTML, that is, E can be body. The selector always hits the first E child of the parent element, regardless of whether the first child is E

Type Indicates other types

  • E:last-of-type {sRules} matches the last sibling element E of the same type.
  • E:only of type {sRules} matches the only sibling element E of the same type.
  • E:nth-of-type(n) {sRules} matches the NTH sibling element E of the same type.
  • E:nth-last-of-type(n) {sRules} matches the penultimate sibling element E of the same type.

UI state pseudo class

  • E: Checked {sRules} Matches the selected element E on the user interface. (used when input type is radio and checkbox)
  • E:enabled {sRules} matches the element E in the available state on the user interface. (mainly for form elements)
  • E:disabled {sRules} matches element E in the disabled state on the user interface. (mainly for form elements)
  • E:target {sRules} matches the E element pointed to by the relevant URL. The URL, followed by the anchor point #, points to a specific element within the document. The linked element is the target element: the target selector is used to select the currently active target element.

Print class pseudo class (understand)

@page :first {sRules} sets the style to be used on the first page of the page container when printing. Only for the @page rule. This pseudo-class selector allows defining only attributes related to margin, orphans, Widows, and Page breaks

@page :left {sRules} sets the style to use for all pages where the page container is located to the left of the binding line. Only for the @page rule. This pseudo-class selector allows defining only margin, padding, border, and background attributes

@page :right {sRules} sets the style to be used for all pages where the page container is located to the right of the binding line. Only for the @page rule. This pseudo-class selector allows defining only margin, padding, border, and background attributes

Pseudo element selector

E:first-letter/E::first-letter { sRules }

Sets the style of the first character in the object. This pseudo-object only works on block objects. For an inline object to use this pseudo-object, it must first be set as a block-level object. This pseudo-class is often used in conjunction with the font-size and float properties to create a drop header effect.

There is an explicit BUG in IE6’s use of this selector: the selector cannot be placed next to the curly braces containing the rule, requiring space or line breaks. Selectors for this BUG include E:first-line

CSS3 distinguishes pseudo-class Selectors from single colons (:) by changing them to double colons (:), but the previous notation is still valid.

E:first-letter can be translated into E::first-letter

p:first-letter {float:left;font-size:40px;font-weight:bold;line-height:1; }p::first-letter {float:left;font-size:40px;font-weight:bold;line-height:1; }Copy the code

E:first-line/E::first-line { sRules }

Sets the style of the first line inside the object. This pseudo-object only works on block objects. For an inline object to use this pseudo-object, it must first be set as a block-level object.

There is an explicit BUG in IE6’s use of this selector: the selector cannot be placed next to the curly braces containing the rule, requiring space or line breaks. Selectors for this BUG include E:first-letter

CSS3 distinguishes pseudo-class Selectors from single colons (:) by changing them to double colons (:), but the previous notation is still valid.

E:first-line can be converted to E::first-line

p:first-line {color:# 090; }p::first-line {color:# 090; }Copy the code

E:before/E::before { sRules }

Sets what happens in front of the object (according to the logical structure of the object tree). Used with the Content attribute and must be defined

CSS3 distinguishes pseudo-class Selectors from single colons (:) by changing them to double colons (:), but the previous notation is still valid.

E:before translates to E::before

<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            p{
                position:relative;
                color:#f00;
                font-size:14px;
            }
            p:before{
                position:absolute;
                background:#fff;
                color:# 000;
                content:"If you can see this text, your browser only supports E:before.";
                font-size:14px;
            }
            p::before{
                position:absolute;
                background:#fff;
                color:# 000;
                content:"If you can see this text, your browser supports E:before and E::before.";
                font-size:14px;
            }
        </style>
    </head>
    <body>
        <p><span>Sorry, your browser does not support E:before and E::before</span></p>
    </body>
</html>
Copy the code

As shown, when the browser supports before, the previous file is covered because the content is set to float.

E:after/E::after { sRules }

Sets what happens after the object (according to the logical structure of the object tree). Used with the Content attribute and must be defined

CSS3 distinguishes pseudo-class Selectors from single colons (:) by changing them to double colons (:), but the previous notation is still valid.

E:after can be converted to E::after

E::placeholder { sRules }

Sets the style of object text placeholders. ::placeholder placeholder elements are used to control the appearance of form input field placeholders, which allow developers/designers to change the style of text placeholders. The default text placeholders are light gray.

It may not be obvious when the form background color is a similar color, so you can use this pseudo-element to change the color of the text placeholder.

Note that, with the exception of Firefox, which is ::[prefix]input-placeholder, other browsers use ::[prefix]input-placeholder Firefox support this pseudo-element with text-overflow properties to handle overflow issues.

input::-webkit-input-placeholder {
	color: # 999;
}
input:-ms-input-placeholder { // IE10+
	color: # 999;
}
input:-moz-placeholder { // Firefox4-18
	color: # 999;
}
input::-moz-placeholder { // Firefox19+
	color: # 999;
}
Copy the code

E::selection { sRules }

Sets the style of the object to be selected. Note that ::selection can only define background-color, color, and text-shadow when selected (IE11 does not support this yet).

<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            p::-moz-selection{
                background:# 000;
                color:#f00;
            }
            p::selection{
                background:# 000;
                color:#f00;
            }
        </style>
    </head>
    <body>
        <h1>Select the text below to see its color</h1>
        <p>After you select the text, look at the text color and background color to see what :: Selection works.</p>
    </body>
</html>
Copy the code

The difference between first-child and :first-of-type

(1) Different ranges can be matched

First-of-type matches the body element, but first-child does not

<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            body:first-of-type {
                background:gray;
                color:#f00;
            }
            body:first-child {
                background:blue;
                color:#f00;
            }
        </style>
    </head>
    <body>
        <div>
            <h1>Second child element</h1>
            <p>First child element</p>
            <h1>Second child element</h1>
            <span>Third child element</span>
            <span>Fourth child element</span>
        </div>
    </body>
</html>
Copy the code

As you can see, only the first-of-type style currently matches the body element.

(2) Structural limitations

A :first-child match requires that the current element be the first child, whereas first-of-type does not

<! DOCTYPEhtml>
<html lang="zh-cmn-Hans">
    <head>
        <meta charset="utf-8" />
        <style>
            p:first-of-type {
                background:# 000;
                color:#f00;
            }
            p:first-child {
                background:# 000;
                color:#f00;
            }
        </style>
    </head>
    <body>
        <div>
            <h1>Second child element</h1>
            <p>First child element</p>
            <h1>Second child element</h1>
            <span>Third child element</span>
            <span>Fourth child element</span>
        </div>
    </body>
</html>
Copy the code

The p tag matches only first-of-Type, not first-Child, because it is not the first child of the parent div of the current P element.