search
HomeWeb Front-endCSS TutorialDetailed explanation of CSS selector Selector

Detailed explanation of CSS selector Selector

Dec 19, 2017 am 10:30 AM
cssselectorSelector

To use CSS to achieve one-to-one, one-to-many or many-to-one control of elements in HTML pages, you need to use CSS selectors. Elements in HTML pages are controlled through CSS selectors. This article mainly introduces the relevant information of CSS Selector in CSS study notes. Friends who need it can refer to it. I hope it can help everyone.

The selector defined in CSS1

Type selector

is used to select elements of a specified type (in fact, it is an html tag selector). Common usage is as follows :

body {
    /*对 body 元素定义样式*/
}

body,p {
    /*同时选择多种标签元素*/
}

ID selector

is used to select the html element with the specified ID. Common usage methods are as follows:

<p>
    
</p>

<style>
    #nav {
        /*定义 ID 为 nav 的元素的样式*/
    }
</style>

Because the rendering order of CSS is from right to left. , and the ID is completely unique, then the previous type selector can be omitted.

Class selector

is used to select html elements with specified class names. Common usage methods are as follows:

<p>
    
</p>

<style>
    .nav {
        /*定义 class 为 nav 的元素的样式*/
    }
</style>

Include selector

Use For selecting hierarchically nested elements, common usage methods are as follows:

<p>
    </p><p>
        
    </p>


<p>
    </p><p>
        </p><p>
        
        </p>
    


<style>
    .nav .nav-tools {
        /*定义元素的父级元素 class 包含 nav,且子元素class 包含 nav-tools 的元素*/
    }
</style>

It should be noted that the included selector does not care about the level, as long as the subsequent selector is included in the previous element. As in the above example, both nav-tools will be selected by the selector!

Pseudo-class selector

:link——Link pseudo-class selector

is used to define the style when the link is not visited. Common usage methods are as follows :

<p>
    </p><p>
        </p>
                
  •         
    

:visited——Link pseudo-class selector

is used to define the visited link style. Common usage methods are as follows:

<style>
    a:visited {
        text-decoration: none;
        color: red;
    }
</style>

:active——User Operation pseudo-class selector

is used to define the activated element style. Common usage methods are as follows:

<style>
    a:active {
        text-decoration: none;
        color: green;
    }
</style>

:hover——User operation pseudo-class selector

is used for Define the style of the element when the mouse passes over it. Common usage methods are as follows:

<style>
    a:hover {
        text-decoration: none;
        background-color: #F4F4F4;
    }
</style>

:focus——User operation pseudo-class selector

is used to define the style of the element that gets focus. Common usage methods are as follows:

<style>
    input:focus {
        text-decoration: none;
        background-color: #F4F4F4;
    }
</style>

::first-line

is used to define the style of the first line of text within the element. Common usage methods are as follows:

<p>
    </p><p>层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。CSS不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化。</p>


<style>
    .doc {
        width: 360px;
    }
    .doc>p::first-line {
        color: red;
    }
</style>

::=first-letter

is used to define the style of the first character in the element. Common usage methods are as follows:

<style>
    .doc {
        width: 360px;
    }
    .doc>p::first-letter {
        font-size: 2em;
        color: red;
    }
</style>

Selector defined in CSS2

*——Wildcard selector

Used to define common styles for all elements in the DOM. Common usage methods are as follows:

<p>
    </p><p>
        </p>

                 

    

If you want to reset the default style, it is not recommended to use wildcard selectors

[attribute]——Attribute selector

is used to define the style of elements containing attributes with attributes. Common usage methods are as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

[attribute="value"]— —Attribute selector

is used to define the value of an element attribute as a specified value style. Common usage methods are as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

[attribute~="value"]——Attribute selector

is used to define attributes that contain specified values ​​and separate attribute value elements with spaces. Common usage methods are as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

As shown above, only the foreground color of the first li will be defined as red !

[attribute|="value"]——Attribute selector

is used to define attribute values ​​that contain the specified value and are linked with a hyphen (-). Common usage methods are as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

As shown above: Only the foreground color of the second li will be defined as red!

:first-child——structural pseudo-class selector

is used to define the style of the first element of the element. Common usage methods are as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

Note: first -child acts on the first element of the same level and with the same label. As shown above, if you want to define the style of the first li, you need to use li:first-child instead of ul:first-child!

:lang(en)

For defining the element style with attribute lang="en", the common usage methods are as follows:

<p>
    </p><p>Hello World</p>


<style>
    p:lang(en) {
        color: red;
    }
</style>

::before

For defining the content and style before the element, the common usage methods are as follows:

<p>
    <a>World</a>
</p>

<style>
    a::before {
        content: "Hello ";
    }
</style>

::after

is used to define the content and style after the element. Common usage methods are as follows:

<p>
    <a>Hello</a>
</p>

<style>
    a::after {
        content: "World";
    }
</style>

p > p

is used to define The style of the first-level child element of the element. The common method is as follows:

<p>
    </p><p>
        </p>

            

                    
  • Menu
  •                 
  • Index
  •             
             

h1 + p

is used to define the style of elements adjacent to the element. The common method is as follows:

<p>
    </p><h1 id="CSS">CSS</h1>
    <p>层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。</p>


<style>
    h1 + p {
        color: red;
    }
</style>

CSS3 New attribute selector

[foo^="bar"]

Used to define the style of elements whose element attributes start with bar

<p>
    <a>Betterde Inc.</a>
    <a>Betterde Inc.</a>
</p>

<style>
    a[href^="https"] {
        color:green;
    }
</style>

As shown above, mark https links in green.

[foo$="bar"]

Used to define the style of elements whose element attributes end with bar

<p>
    <a>logo.png</a>
    <a>style.css</a>
    <a>main.js</a>
</p>

<style>
    a[href$="png"] {
        background: url(system/filetype/png.png) no-repeat left center;
        padding-left: 18px;
    }
    
    a[href$="css"] {
        background: url(system/filetype/css.png) no-repeat left center;
        padding-left: 18px;
    }
    
    a[href$="js"] {
        background: url(system/filetype/js.png) no-repeat left center;
        padding-left: 18px;
    }
</style>

As shown above, identify the linked hyperlinks File format and add the file type icon in front!

[foo*="bar"]

is used to define the style of the element containing bar in the element attribute. It should be noted that here it is included, that is to say, no matter what it is Combination, as long as the attribute value and the three consecutive letters of bar will be selected!

<p>
    </p><h1></h1>
    <h2>
    <h1></h1>

<style>
    a[class*="title"] {
        color: red;
    }
</style>
</h2>

As shown above: the three elements within p will be rendered as red fonts!

Although CSS3 still retains the attribute selectors defined in CSS2, it is recommended to use CSS3 attribute selectors instead!

Structure pseudo-class selector

:root

Used to define the style of html tag elements

:nth-child(n)

is used to define the style of sub-elements, n represents the sub-element. n can be a number, or the keyword odd, even, or a formula. Common usage methods are as follows:



    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    
namegenderage
GeorgeMale23
KevinMale28
AnguleMale23

:nth-last-child(n)

与 :nth-child(n)用法相同,只是排序方式是从后往前!

:nth-of-type(n)

用于定义相同元素的第 n 个元素的样式,常见使用方法如下:



    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    
namegenderage
GeorgeMale23
KevinMale28
AnguleMale23

:nth-last-of-type(n)

与 :nth-of-type(n)用法相同,只是排序方式是从后往前!

:last-child

用于定义最后一个元素的样式,常见使用方法如下:



    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    
namegenderage
GeorgeMale23
KevinMale28
AnguleMale23

:first-of-type

定义第一个元素相同类型元素的样式,与 :nth-of-type(1) 效果一样

:last-of-type

定义最后一个元素相同类型元素的样式,常见使用方法如下:



    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    
namegenderage
GeorgeMale23
KevinMale28
AnguleMale23

:only-child

用于定义子元素只有一个且与制定元素标签相同,常见使用方法如下:

<p>
    </p><h1 id="Hello">Hello</h1>


<style>
    h1:only-child {
        /*如果 p 中还有其他任何元素,则h1不会按照该选择器中定义的样式渲染*/
    }
</style>

:only-of-type

用于定义只包含一个制定的标签元素的样式,常见使用方法如下:

<p>
    </p><h1 id="Hello">Hello</h1>


<style>
    h1:only-of-type {
        /*如果 p 中还有其他任何元素,则h1不会按照该选择器中定义的样式渲染*/
    }
</style>

:empty

用于定义,一个元素中没有包含任何子元素的样式,常见使用方法如下:

<p>
    
</p>

<style>
    p:empty {
        display: none;
    }
</style>

CSS3 新增的其他选择器

E ~ F

用于定义兄弟元素的样式,常见使用方法如下:

<p>
    </p><p>Hello</p>

<p>CSS</p>

<style>
    p ~ p {
        color: red;
    }
</style>

p 元素中的 p 不会被渲染为红色字体,只有跟 p 是同级的 p 才会被渲染为红色!

:not(s)

用于定义指定元素,并且过滤 s 所指定的选择器元素,常见使用方法如下:

<p>
    </p><p>Hello</p>
    <p>World</p>
    <p>Welcome!</p>


<style>
    p:not(.red) {
        color: blue;
    }
</style>

注意:s 是一个简单的结构选择器,不能使用复合选择器,该选择器只匹配第一个复合条件的元素。如上所示,最后一个 p 不会被渲染为蓝色!

:target

用于定义被访问的锚链样式,常见使用方法如下:

<p>
    </p><p>
        </p>

这是第一个文本段

         

        

这是第二个文本段

    

注意:当我们激活锚链时(url中包含 #text-one 或 #text-two),对应的 p 内的元素字体会被渲染为红色!

CSS3 UI 元素状态伪类选择器

:enabled

用于定义元素的 enabled 时的样式,常见使用方式如下:

<p>
    <input>
</p>

<style>
    input:enabled {
        background: #ffff00;
    }
</style>

注意:元素默认状态为 enabled

:disabled

用于定义元素处于禁用状态时的样式,常见使用方法如下:

<p>
    <input>
</p>

<style>
    input:disabled {
        background: #dddddd;
    }
</style>

:checked

用于定义元素被选中时的样式,常见使用方式如下:

<p>
    </p>
             

相关推荐:

CSS选择器中带点(.)的解决办法

Css选择器

关于css选择器的那些事

The above is the detailed content of Detailed explanation of CSS selector Selector. 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
In Defense of the Ternary StatementIn Defense of the Ternary StatementApr 22, 2025 am 11:25 AM

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Using the Web Speech API for Multilingual TranslationsUsing the Web Speech API for Multilingual TranslationsApr 22, 2025 am 11:23 AM

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

Jetpack Gutenberg BlocksJetpack Gutenberg BlocksApr 22, 2025 am 11:20 AM

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

All About mailto: LinksAll About mailto: LinksApr 22, 2025 am 11:04 AM

You can make a garden variety anchor link () open up a new email. Let's take a little journey into this feature. It's pretty easy to use, but as with anything

It's pretty cool how Netlify CMS works with any flat file site generatorIt's pretty cool how Netlify CMS works with any flat file site generatorApr 22, 2025 am 11:03 AM

Little confession here: when I first saw Netlify CMS at a glance, I thought: cool, maybe I'll try that someday when I'm exploring CMSs for a new project. Then

Testing for Visual Regressions with PercyTesting for Visual Regressions with PercyApr 22, 2025 am 11:02 AM

It’s a Herculean task to test

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor