search
HomeWeb Front-endJS TutorialSummary of how to use CSS selectors

Summary of how to use CSS selectors

May 25, 2018 am 11:36 AM
cssInstructionsSelector

This time I will bring you a summary of how to use CSS selectors, and what are the precautions for using CSS selectors. The following is a practical case, let's take a look.

CSS selector

1.id selector #id{ }, "#id" selects the element
2. Class selector.class{ }, ".class name" selects Element
3.Tag selector p{ }, "tag name" selected element
4.Wildcard selector { },"" Select all elements
5. Combined selector:
Group selector E,F "," separated by commas, select E,F elements at the same time
Descendant selector E F separated by spaces , select all F elements under the E element (no matter how many levels the F element is nested, it will still be selected)
Direct sub-selector E > F ">" separates, selects the direct sub-element F under the E element, That is, the first-level sub-element F
adjacent sibling selector under the E element E F, " " separates the directly adjacent element F
after selecting the E element. Common phase Neighbor selectors E ~ F, "~" separates all sibling elements F that follow after selected E element
6. Pseudo-class selector L-V-H-A,:link,:visited, :hover,:active
7. Pseudo-element selector
E::first-line Selects the first line of the E element content
E::first-letter Selects the first letter of the E element content
E::before Insert content before the E element
E::after Insert content after the E element
Before and after are locations where additional content can be inserted and need to be used with the content attribute
8 .Attribute selector
input[type="text"] {
width:150px;
}


Priority of the selector

Css selector priority core: Each selector has its own priority. The more specific the scope, the higher the priority.
CSS priorities from high to low are:
1. Using !important after an attribute will override the element style defined anywhere on the page.
2. Inline style written on element tag as style attribute
3.id selector
4. Class selector
5. Pseudo-class selector
6. Attribute selector
7. Tag selector
8. Wildcard selector
9. Browser customization
When the CSS style rule consists of multiple selectors, the weight of the id selector is 1000. The class selector is 100 and the label selector is 10. Which one takes priority is determined by the sum of the weights. When the weights of two CSS rules are the same, which one is more specific will be used, that is, the selector with a higher weight will be more specific and have a higher priority. When the two selector rules and weights are the same, the later style will overwrite the previous one!
p {color: #333;}
p {color: #666;}
In this way, the color of the p copy will obviously be #666


class and id usage scenarios

id is a unique identifier on the page, and class identifies a certain type of style on the page. It is universal and can be used repeatedly. The class name of an element can be written as class="intro other", that is, there can be multiple class names, which means superimposing the styles corresponding to the two class names. The id name cannot be written like this. ID names are often used in page layouts (marking large frames), and classes are generally used in local page layouts for style definition. Because the class names can be written the same when naming, you only need to write the style once for the class, and it can be used by everyone. Reuse elements of the same style. Delimit appropriate namespaces when using CSS selectors to improve code readability and facilitate maintenance


Examples of selector usage

html
#header{} /*选中id为header的元素*/
.header{}    /*选中class=header的元素*/ 
.header .logo{}  /*选中class=header下的所有class=logo的元素*/ 
.header.mobile{}  /*选中class="header mobile"的元素*/ 
.header p, .header h3{}  /*选中class=header元素下的所有p元素,同时选中class=header元素下的所有h3元素*/ 
#header .nav>li{}  /*选中id=header元素下的所有class=nav元素的直接子元素li*/ 
#header a:hover{}  /*选中id=header元素下的所有a元素,并使用hover伪类*/

Common pseudo-class selectors

【1】Structural pseudo-class selectors
E: first-child selects the first child element under the parent element where E is located, and the child element is the E element
E:last-child selects the last child element under the parent element where E is located, and the child element is the E element
E:root selects the element of the root node where E is located. For HTML, it selects the HTML element.
E:nth-child(n) selects the nth child element under the parent element where E is located, and the child element is the E element.
E:nth-last-child(n) Selects the nth child element from the bottom under the parent element where E is located, and the child element is the E element
E:nth-of-type(n) Selects the parent element where E is located The nth E element among the elements of the same type under the element
E:nth-last-of-type(n) Selects the nth E element from the bottom among the elements of the same type under the parent element where E is located
E:first-of-type Selects the first E element among the elements of the same type under the parent element where E is located
E:last-of-type Selects the last E element among the elements of the same type under the parent element where E is located
E:only-child matches the only child element within the parent element, which is equivalent to: first-child:last-child or:nth-child(1):nth-last-child(1)
E :only-of-type matches the only child element using the same tag under the parent element, which is equivalent to :first-of-type:last-of-type or :nth-of-type(1):nth-last-of -type(1)
E:empty matches an element that has no child elements, and the element does not have any text nodes
E:not(F) matches any element that does not match the current selector
[2]Dynamic pseudo-class selector Sequence L-V-H-A
link-visited-hover-active

a:link{
 color:red;
 }
 
 a:visited{
 color:blue;
 }
 
 a:hover{
 color:gree;
 font-size:20px;
 }
 
 a:active{
 color:gold;
 }
 a:focus{
 color:gold; //a元素获得焦点后的样式
 }

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

E:first-child specifies the element E and finds the first E element under its parent element
E: first-of-type specifies the element of E type and finds the E type under its parent element The first


code example of the element:

html
<style>
.item1:first-child{ color: red;}
.item1:first-of-type{ background: blue;}
</style> 
<p> 
</p><p>aa</p>
<h3 id="bb">bb</h3>
<h3 id="ccc">ccc</h3> 

Summary of how to use CSS selectors

.item1:first-child{color :red;}class=The first child element item1 font under the parent element p of the item1 element is red<h3 id="bb-h-h-ccc-h">bb<h3>,<h3>ccc<h3></h3> </h3> </h3> </h3>Although class =item1 but they are not the first child element under its parent element.

.item1:first-of-type{background:blue;}The first class=item1 element among the elements of the same type under the parent element of the class=item1 element. <p class="item1">aa</p> Select the first element (p, h3) of the same type under the parent element p, namely aa, bb, with a blue background.


text-align: The role of center

Sets the horizontal center alignment of the text within the element. text-align is applied to block-level elements (p or p). The alignment of the internal inline elements (text, pictures, input boxes) of this block-level element (p/p) can be set.
text-align has 5 values: left/right/center/justify/inherit, left-aligned/right-aligned/center-aligned/aligned at both ends/inherit parent element align value. When justifying both ends, the word spacing in each line may be inconsistent.


I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to handle the MySQL database access denial

Detailed explanation of the steps to use the front-end testing pyramid

The above is the detailed content of Summary of how to use CSS selectors. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment