A combination of selectors and selectors

In our daily work, CSS is not used as much as JS, but it can not be underestimated. CSS knowledge is more, we have selected a few of the more common points to introduce you, hoping to help you better understand the use of CSS. Without further ado, let’s begin!

The selector

The basic meaning of a selector is to select a group of elements in the element tree based on some characteristics.

Selectors can be divided into the following structures:

  • Simple selector: Determines whether elements are selected for a feature.

  • Compound selectors: Simple selectors written consecutively together that select individual elements for their own characteristics.

  • Complex selector: by, >, ~ +, | | symbols such as connection in line with the selector, according to the parent element or sequence elements inspection before a single element.

  • Selector list: Complex selectors separated by, representing or relationships.

Essence: A selector is a hierarchical structure composed of simple selectors

Simple selector

Simple selectors are common type selectors, total selectors, ID selectors, class selectors, attribute selectors, pseudo-class selectors.

Type selector

The type selector selects an element based on its tag name, such as

,

, .

// example
div {
    width: 100%;
}

p {
    font-size: 32px;
}

img {
    width: 100%;
    height: 100%;
}
Copy the code

All selector

The universal selector (also known as wildcard selector) * can select any element, and is used exactly the same way as the type selector.

// example
* {
  margin: 0;
  padding: 0;
}
Copy the code

The id selector

The ID selector is a “#” followed by the ID name.

// example
#myid {
    stroke:blue;
    stroke-width:1;
}
Copy the code

The class selector

The class selector is “. This is followed by the class name.

// example
.mycls {
    font-size:40px
}
Copy the code

Property selector

Attribute selectors select HTML elements based on their attributes. Let’s start by defining a simple DOM structure to understand the use of property selectors.

/ / the DOM structure<h1>Title 1 does not have the title attribute</h1>
<h2 title='h'>Title 2 has the title attribute</h2>
<h3 title='h three'>Title 3 has the title attribute</h3>
<a href=The '#' title='a'>Links have title attributes</a>
<a href="#" lang="zh-TW">Hyperlinks are hyphenated</a>
Copy the code

Property selectors have four forms:

  • [att]

Putting the attribute name in square brackets checks whether the element has the attribute. If the element has the attribute, it can be selected regardless of the value of the attribute.

// All elements with the title attribute can be selected to set the text color to red
[title] {
    color: red;
}
Copy the code
  • [att=val]

For exact matching, check if the value of an element attribute is val.

// All elements that have the title attribute and whose title value is a can be selected with the text color set to blue
[title=a] {
    color: blue;
}
Copy the code
  • [att~=val]

There are many values (separated by Spaces) for an attribute of an element, as long as one of these values matches val.

// The element with the title attribute and three in the attribute value (separated by space) can be selected to set the color of the text to green
[title~=three] {
    color: green;
}
Copy the code
  • [att|=val]

Initial matching: checks whether an element’s value starts with val. The difference between exact matching is that attributes only start with val.

// An element with a title attribute whose value starts with h can be selected to set the text background to PINK.
[title|=h] {
    background: pink;
}
Copy the code

Pseudo class selector

Pseudo-class selectors are a series of CSS-specified selectors starting with:. Pseudo – class selectors have two types: ordinary and functional. We will cover only a few common pseudo-class selectors here.

Links to related

Element position correlation

Start by defining a simple DOM structure for understanding pseudo-class selectors related to element positions.

<ul>
    <li> node1 </li>
    <li> node2 </li>
    <li> node3 </li>
    <li> node4 </li>
    <li> node5 </li>
    <li> node6 </li>
    <li> node7 </li>
    <li> node8 </li>
</ul>
Copy the code
  • first-child
// Set the color of the first child node (
  • node1
  • ) in the ul list to red
    ul :first-child { color: red } Copy the code
    • last-child
    // Set the color of the last child node in the ul list (
  • node8
  • ) to green
    ul :last-child { color: green } Copy the code
    • NTH – child (condition)
    // Set the color of the child nodes in the ul list to yellow, and set the child nodes that meet the 2n (even condition) to yellow
    ul :nth-child(2n) {
        color: yellow
    }
    Copy the code
    • NTH child (conditions) – the last –

      Similar to nth-child, except that this is counted backwards

    • NTH – of – type (condition)

    • NTH – last – of – type (condition)

      Similar to nTH-of-type, except that this is numbered backwards

    Note the difference between nth-child and nth-child-type

    Of -type series, is a deformation of the syntactic sugar, S: NTH – of – type (An a + B) is: the NTH – child (| | of the An a + B) S a different way of writing

    A combination of selectors

    A list of selectors is a sequence of complex selectors separated by; Complex selector is used, >, ~ +, | | compound selector link; A compound selector is a simple selector combination of concatenation.

    Priority comparison

    • First priority: no join symbol, that is, compound selector.

      A compound selector represents the relationship of and in a simple selector.

    // composite selector
    .a.b {
        color: pink;
    }
    Copy the code

    The code above means that the selected element must have both a and B classes.

    • The second priority:, >, ~ +, | |, namely complex selector.

      A complex selector is a selection for node relationships. It includes five join modes, which we will introduce one by one:

      • : Descendant: indicates that all the descendants that meet the conditions are selectedDescendants of the nodeDescendant nodes refer to all nodes under the current node.
      • >: Indicates that the child is selectedChild nodes, child nodes refer to all nodes at the level below the current node.
      • ~: Successor: indicates that all qualified successor nodes are selected. The successor node has the same parent element as the current node and appears after it.
      • +: Indicates the immediate successor node.
      • ||: column selector, which selects eligible cells in corresponding columns.

      We are more commonly used is offspring and children > these two kinds of connection, let’s take an example 🌰 :

    / / the DOM structure
    <div className='a'>
        <div className='b'>
            <div className='b'>offspring</div>
        </div>
    </div>
    
    // Select all nodes of class A whose class is B
    .a .b {
        width: 100px;
    }
    // Select all nodes of class B at the next level of class A
    .a>.b {
        width: 100px;
    }
    Copy the code
    • Third priority:,, the selector list

      The list of selectors, which represents an “or” relationship, can actually be thought of as a shorthand for “two CSS rules with the same content.” Select the node with class root or root2 and color it gray.

    / / the DOM structure
    <div className='root'>root</div>
    <div className='root2'>root2</div>
    
    / / write 1
    .root,.root2 {
        cilor: grey;
    }
    
    / / write 2
    .rrot {
        color: grey;
    }
    .root2 {
        color: grey;
    }
    Copy the code

    The priority of the selector

    CSS selectors are rules-based, and it is quite common for the same element to hit multiple rules. When different rules specify the same attribute with different values, a mechanism is needed to resolve conflicts. This mechanism, which we will talk about next, is selector priority.

    The CSS standard uses a triplet (A, B,c) to form the priorities of complex selectors

    • Let’s call the number of ids a
    • The number of pseudo-classes and classes is denoted as b
    • The number of pseudo-elements and types is denoted by c
    • *The priority is not affected

    The CSS standard recommends using a large enough base to obtain “A-B-C” to indicate selector priority.

    Kt = Base * base * A + Base * b + C.

    Base is a positive integer large enough to ensure that id takes precedence over class and pseudo-class over type and pseudo-element

    * Add-in: Inline attributes always take precedence over CSS rules, and browsers provide a “port” that is added to the selector. Import, which has the highest priority.

    Selectors of the same priority follow the “last overrides the previous” principle

    • The override here refers to the current order in the CSS stylesheet, not the order in the class

    • The priority of a selector is for a single rule. If the selectors of multiple rules hit elements at the same time, the priority does not overlap.

    • The priority of a selector is for a complex selector, and the list of selectors does not combine to calculate the priority.

    Here’s an example:

    / / the DOM structure
    <div class="x y z">text<div>
    
    / / CSS styles
    .x, .z {
        background-color:lightblue;
    }
    .y {
        background-color:lightgreen;
    }
    Copy the code

    There are two points to note in the above code:

    1. Selector list.x..zDiv is hit, but its two entries are prioritized separately, so the final priority is still the same.yThe rules are the same.
    2. because.yThe stylesheet appears at the end, so the final style takes.yThe background color is light green.

    conclusion

    In this section, we describe CSS selectors and their combinations in detail, as well as the preference mechanism for selectors. We’ll move on to other CSS topics.

    I am how to celebrate more than years, if the article has helped you, I hope you can point a thumbs-up, thank you!

    If you have any questions, please discuss them in the comments section.