In this article, we mainly summarize the selectors in CSS.
The selectors in CSS mainly include:
- Derived selectors: Defines a style by the context in which the element is located. Includes descendant selectors, child element selectors, adjacent sibling selectors.
- ID Selector: You can specify a specific style for an HTML element that is labeled with a specific ID.
- Class selector: You can specify a specific style for the HTML element of a class.
- Property selector: Sets the style for the HTML element that owns the specified property, not just the class and ID properties.
(1) Selector grouping: You can group any number of selectors together, separated by ', ' in the middle.
Example: Body, H2, p, table, TH, TD, Pre, Strong, em {color:gray;}
(2) Several usages of class selectors
- In combination with the element selector:
Example: p.important {color:red;}
Matches all P elements of class important, but none of the other types of elements match.
- Multi-Class selector: (not supported before IE7)
Cases:.important.warning {background:silver;}
Matches elements that have the same two class.
(3) Property selector: Match elements based on attributes of elements
- Simple attribute Selection
Example: A[title] {color:red;} Styles are applied only to a element with the title attribute.
- Select based on specific attribute values
Example: Input[name= ' basketball '] selects only elements with specific attribute values.
- The property matches the property value exactly
Example: for <p class= "Important warning" >this paragraph is a very important warning.</p>
Use p[class= "important warning"] {color:red;}
- Match based on partial attribute values
Example: for <p class= "Important warning" >this paragraph is a very important warning.</p>
Use p[class~= "Important"] {color:red;} to select from a word in the list of words in the attribute value.
- Substring Matching Property Selector
input[name^= ' foot ': matches a given property is an element that starts with some value.
input[name$= ' Ball ': matches a given property is an element that ends with some value.
Input[name*= ' sket ': matches the given attribute to an element that contains some value.
(4) Descendant selector
Example: H1 em {color:red;}, matching all em in H1 descendants
Example: H1 > Strong {color:red;}, select the strong element only as a child element of the H1 element.
(5) Adjacent Brother Selector
Example: H1 + P {margin-top:50px;}, matches the P element that appears after the same parent element, H1.
(6) Pseudo-class
such as a linked: visited,: hover, Input: Focus,: Checked,:d isabled, etc.,: first-child,: First-of-type,: Nth-of-type, Nth-child,: Before,: After and so on.
CSS Basics points (ii)