Home > Web Front-end > CSS Tutorial > css pseudo-selector learning pseudo-class selector analysis

css pseudo-selector learning pseudo-class selector analysis

青灯夜游
Release: 2022-08-03 11:27:03
Original
2575 people have browsed it

In the previous article "css pseudo-selector learning: Pseudo-element selector analysis", we learned about pseudo-element selectors, and today we learn more about pseudo-class selectors. I hope it will be useful to everyone. Helps!

css pseudo-selector learning pseudo-class selector analysis

Pseudo-class selector

Pseudo-class selector is a type of selector that allows passing code that is not included in HTML Element state information to locate the usage of HTML elements. Pseudo-class selector The specific usage is to add keywords to the existing selector to represent the status information of the positioned HTML element. [Recommended learning: css video tutorial]

Through pseudo-classes, developers can set the dynamic state of elements, such as hover (hover), click (active), and other elements that cannot be passed in the document. The elements selected by the selector (these elements have no ID or class attributes), such as the first child element (first-child) or the last child element (last-child).

For example:hoverThe pseudo-class selector can be used to change the color of the button when the user hovers the mouse over the button. As shown in the following sample code:

/* 所有用户指针悬停的按钮 */  
 button:hover {  
  color: blue;  
 }
Copy after login

The name of the pseudo-class is not case-sensitive, but needs to start with a colon :. In addition, pseudo-classes need to be used in conjunction with selectors in CSS. The syntax format is as follows:

选择器:伪类 {  
  属性 : 属性值;  
 }
Copy after login

The specific syntax format of pseudo-class selector is :pseudo-class, Don’t forget : here.

CSS provides a variety of pseudo-classes, as shown in the following table:

##:first- of-typep:first-of-type Matches the first

element in the parent element

:focusinput:focus Matches the focused <input> element:hovera:hover Match the element on which the mouse is hovering :in-rangeinput:in-rangeMatch elements with the specified value range <input> element:invalidinput:invalid Matches all <input> elements#:lang(language):last-child:last-of-type:link:not(selector) :nth-child(n):nth-last-child(n):nth-last-of-type(n)##:nth-of-type(n)p:nth-of-type(2)match The second child element of the parent element

:only-of-typep:only-of-type matches the parent The only

element in the element

:only-childp:only-child matches the only child element in the parent element

:optionalinput:optional Matches <input> elements without the "required" attribute:out-of-rangeinput:out-of-range Matches <input> elements with values ​​outside the specified range:read-onlyinput:read-only Matches <input> elements that specify the "readonly" attribute:read-writeinput:read-write Matches <input> elements without the "readonly" attribute :requiredinput:required Matches <input> elements that specify the "required" attribute:root root matches the root element of the element. In HTML, the root element is always HTML:target#news:target Matches the currently active #news element (clicked on a URL containing this anchor name) :validinput:valid Matches all An <input> element with a valid value:visiteda:visitedmatches all visited links

Classification of pseudo-class selectors

The CSS version has evolved from the first version to the third version, providing pseudo-class selectors## The number of # is already huge. In particular, the CSS3 version has added a large number of pseudo-class selectors.

There are so many pseudo-class selectors. In order to better sort out the pseudo-class selectors, we can divide them into the following 5 types according to their uses:

    <li>User behavior pseudo-classes: refers to some pseudo-classes related to user behavior, for example, hover

    :hover, press:active And get focus:focus etc.

    <li>URL positioning pseudo-class: used to locate elements in HTML pages

    <li>Input pseudo-class: pseudo-class related to form controls

    <li> Structure pseudo-class: Mainly used to locate target elements

    <li>Logical combination pseudo-class: Used for logical operations, such as

    :not( ), it means it is not a certain element.

1. User behavior pseudo-class - dynamic pseudo-class selector

The reason why it is called dynamic pseudo-class Selectors, because they match elements based on changing conditions, are relative to the fixed state of the document. As JavaScript is widely used to modify document content and element state, the boundaries between dynamic selectors and static selectors are becoming increasingly blurred. However, dynamic pseudo-class selectors are still a special type of selector.

: The link selector matches hyperlinks, and the :visited selector matches hyperlinks that the user has visited.

Usage: There are not many attributes that the visited selector can be applied to link elements. You can change the colors and fonts, but that's about it.

Tips: The visited selector matches any link whose href attribute is a URL that the user has visited on all pages, not just your page. The most common use of :visited is to apply a certain style to visited links to distinguish them from unvisited links. For example, when we watch the news, the status of the news that we have read and the news that we have not read are different in the homepage list, which makes it easier for us to distinguish.

: hover selector

: The hover selector matches any element that the user mouse is hovering over.

: active selector

: The active selector matches the element currently activated by the user (usually the element is clicked by the mouse).

: focus selector

: The focus selector matches the element that has received focus, and is often used for input elements.

2. Structural pseudo-class selector

Use the structural pseudo-class selector to select elements based on their position in the document. This type of selector is prefixed by a colon character (:), for example: empty. They can be used alone or in combination with other selectors, such as p:empty.

Structure pseudo-class selector The content contained in the class selector is as shown in the following table:

Selector Example Example description
:active a :active match clicked link
:checked input:checked match the selected
:disabled input:disabled matches every disabled <input> element
:empty p:empty Matches any

element that has no child elements

:enabled input:enabled Matches every enabled <input> element
:first-child p:first-child Matches the first child element

in the parent element,

must be the first child element in the parent element

## that have an invalid value
p:lang(it) Match every

element whose lang attribute value starts with "it"

p:last-child Matches the last child element

in the parent element,

must be The last child element in the parent element

p:last-of-type matches the The last

element

a:link matches all unvisited links
:not(p) Match every element that is not a

element

p:nth-child(2) Matches the second child element in the parent element

p:nth-last-child(2) Matches the penultimate child element of the parent element

p:nth-last-of-type(2) Matches the penultimate element of the parent element Child element

Pseudo-class selector Function is used to locate a group of sibling elements The first element of is used to locate the last element in a group of sibling elementsUsed to locate the nth element in a group of sibling elementsUsed to locate the nth element in a group of sibling elements in reverse order Used to locate the first element in a group of sibling elements of the same typeUsed to locate the last element in a group of sibling elements of the same typeUsed to locate the nth element in a group of sibling elements of the same type Used to locate the nth element in reverse order among a group of sibling elements of the same typeUsed to locate an element without any sibling elements Used to locate an element that does not have any sibling elements of the same type Used to locate an element An element that has no child elements and does not have any text content is used to locate the root of the HTML page Element (

CSS中的结构伪类选择器是根据HTML页面中元素之间的关系来定位HTML元素,从而减少对HTML元素的id属性和class属性的依赖。

:first-child与:last-child

:first-child伪类用来定义一组兄弟元素的第一个元素而:last-child伪类则是定位一组兄弟元素的最后一个元素。

如下示例代码展示了:first-child伪类和:last-child伪类的用法:

HTML结构如下:

Copy after login
        <li>涂山红红     <li>涂山苏苏     <li>涂山蓉蓉     <li>涂山雅雅

CSS代码如下:

li:first-child {
    color: red;
}
li:last-child {
    color: blue;
}
Copy after login

代码运行结果如下图所示:

css pseudo-selector learning pseudo-class selector analysis

:first-child 伪类可以使用:nth-child(n)伪类改写为:nth-child(1),而:last-child伪类可以使用:nth-last-child(n)伪类改写为:nth-last-child(1)

:first-child伪类和:last-child伪类经常会引起误解。例如 li:first-child 是用来定位所有<li>元素中第一个作为子级元素的,而不是定位<li>元素的第一个子级元素。

:first-of-type与:last-of-type

:first-of-type伪类和:last-of-type伪类一个用于定位一组元素中的第一个兄弟元素,一个用来定位最后一个。

如下示例代码展示了:first-of-type伪类和:last-of-type伪类的用法:

HTML结构如下:

<h3>狐妖小红娘</h3>
<p>涂山红红</p>
<p>涂山苏苏</p>
Copy after login

CSS代码如下:

p:first-of-type {
    color: red;
}

p:last-of-type {
    color: blue;
}
Copy after login

代码运行结果如下图所示:

css pseudo-selector learning pseudo-class selector analysis

:first-of-type伪类与:last-of-type伪类的用法一定要和:first-child伪类与:last-child伪类的用法区分开。以:first-of-type伪类和:first-child伪类为例来说明:

    <li>

    :first-of-type伪类是定位一组同类型的兄弟元素中的第一个元素,不管这个元素在兄弟元素中的位置如何。

    <li>

    :first-child伪类是定位一组兄弟元素中的第一个元素,这些兄弟元素不一定是同类型的。

如果将上述示例代码中的:first-of-type伪类改写为:first-child伪类的话,将不会生效。

:nth-child(n)与:nth-last-child(n)

:nth-child(n)伪类和:nth-last-child(n)伪类都是CSS3中新增的选择器,这两个选择器的用法基本上是一致的。区别在于:nth-last-child(n)伪类是倒序方式定位元素,也就是说,:nth-last-child(n)伪类是从一组元素的结尾开始的。

接下来,主要以:nth-child(n)伪类为例进行讲解。:nth-child(n)伪类中的n参数的含义具有3种情况:

    <li>

    数字值:任意一个大于 0 的正整数。例如 #example td:nth-child(1) 表示定位ID为example的父元素下所有

selector:first-child
selector:last-child
selector:nth-child(n)
selector:nth-last-child(n)
selector:first-of-type
selector:last-of-type
selector: nth-of-type(n)
selector: nth-last-of-type(n)
selector:only-child
selector:only-of-type
selector:empty
selector:root )
元素中的第一个元素。<li>

关键字:odd表示奇数,等同于:nth-child(2n)even表示偶数,等同于:nth-child(2n+1)

<li>

格式为(an+b)公式:a表示周期的长度(步长 ),n表示计数器(从 0 开始 ),而b则表示偏移值。

如下示例代码展示了:nth-child(n)伪类(实现表格隔行换色效果)的用法:

nbsp;html>



    <meta>
    <meta>
    <meta>
    <title>nth-child伪类</title>
    <style>
        table {
            border-collapse: collapse;
            border-spacing: 0;
            width: 100%;
        }

        th,
        td {
            border-top: 1px solid lightcoral;
            text-align: center;
        }

        /* 最后一行单元格在底部增加一个边框效果 */
        tr:last-child td {
            border-bottom: 1px solid lightcoral;
        }

        /* 实现隔行换色 */
        tr:nth-child(even) {
            background-color: aquamarine;
        }
    </style>



    
Copy after login
                                                                                                                                                                                                                                
姓名区域
梵云飞西西域
欢都落兰南国
石宽北山
涂山红红涂山

代码运行结果如下图所示:

css pseudo-selector learning pseudo-class selector analysis

:nth-child(n)伪类的n参数用法中比较复杂的是使用(an+b)公式用法,如下示例列举了一些公式用法:

    <li>

    :nth-child(5n):定位元素的序号是5 [=5×1]、10 [=5×2]、15 [=5×3]等。

    <li>

    :nth-child(3n+4):定位元素的序号是4 [=(3×0)+4]、7 [=(3×1)+4]、10 [=(3×2)+4]、13 [=(3×3)+4] 等。

    <li>

    :nth-child(-n+3):定位元素的序号是3 [=-0+3]、2 [=-1+3]、1 [=-2+3]。

:nth-child(n)伪类与:nth-last-child(n)伪类和:nth-of-type(n)伪类与:nth-last-of-type(n)伪类的区别,类似于:first-of-type伪类与:last-of-type伪类和:first-child伪类与:last-child伪类的区别。

:empty

:empty伪类是用来定位没有任何子级元素或文本内容的元素,其中文本内容包含了空白。但是HTML的注释是不影响:empty伪类定位元素的。

如下示例代码展示了:empty伪类的用法:

nbsp;html>



    <meta>
    <meta>
    <meta>
    <title>empty伪类</title>
    <style>
        body {
            /* 开启flex布局 */
            display: flex;
        }

        .box {
            background: pink;
            height: 80px;
            width: 80px;
            margin: 0 20px;
        }

        .box:empty {
            background: lime;
        }
    </style>



    <div></div>
    <div>这个元素的背景是粉色的</div>
    <div>
        <!-- 这是一个注释 -->
    </div>


Copy after login

代码运行结果如下图所示:

css pseudo-selector learning pseudo-class selector analysis

:root

CSS中的:root伪类选择器比较简单,它代表的就是元素。

如下代码展示的:root伪类的用法:

:root {
    height: 100vh;
    width: 100vw;
    background-color: dodgerblue;
}
Copy after login

代码运行结果如下图所示:

css pseudo-selector learning pseudo-class selector analysis

3、UI元素状态伪类选择器

使用UI伪类选择器可以根据元素的状态匹配元素,下方列表将简单总结这类选择器:

选择器 说明
:enabled 选择启用状态的元素
:disabled 选择禁用状态的元素
:checked 选择被选中的input元素(只用于单选按钮和复选框)
:default 选择默认元素
:valid 根据输入验证选择有效或者无效的input元素
:in-range/:out-of-range 选择在制定范围之内或者职位受限的input元素
:required/:optional 根据是否允许:required属性选择input元素

4、输入伪类选择器

关于表单输入的伪类,主要介绍三种常用的,具体如下:

    <li>

    :enabled:disabled

    <li>

    :read-only:read-write

    <li>

    :checked

:enabled和:disabled

:enabled:disabled一这组伪类选择器分别表示禁用状态与可用状态,这组为了使完全对立的。

:enabled伪类的实际用处并不大,因为大多元素默认都是可用的,所以写不写意义并不大。

如下代码展示了:enabled:disabled的用法:

nbsp;html>



  <meta>
  <meta>
  <meta>
  <title>:enabled和:disabled的用法</title>
  <style>
    input:enabled {
      outline: none;
    }

    input:disabled {
      /* 禁用状态背景为灰色 */
      background-color: gray;
    }
  </style>



  <input>
  <input>


Copy after login

代码运行结果如下所示:

css pseudo-selector learning pseudo-class selector analysis

由上图我们看到禁用状态的<input>的背景颜色为灰色。

:read-only和:read-write

:read-only:read-write一这组伪类选择器分别表示只读和可写状态,同样的:read-write也很鸡肋,因为默认就是可读写,示例代码如下所示:

nbsp;html>



  <meta>
  <meta>
  <meta>
  <title>:read-only和:read-write</title>
  <style>
    input:read-write {
      outline: none;
    }

    /* 只读状态 */
    input:read-only {
      color: red;
      outline: none;
    }
  </style>



  <input>
  <input>


Copy after login

代码运行结果如下所示:

css pseudo-selector learning pseudo-class selector analysis

我们可以看到,只读的<input>的文字颜色为红色。

:checked

:checked伪类可以说是众多伪类选择器中使用频率很高的一个伪类选择器,该选择器表示选中的状态,就比如下面这个例子:

nbsp;html>



  <meta>
  <meta>
  <meta>
  <title>checked伪类</title>
  <style>
    input:checked {
      /* 为选中的增加阴影 */
      box-shadow: 2px 2px 2px 2px lightcoral;
    }
  </style>



  <input>
  <input>


Copy after login

css pseudo-selector learning pseudo-class selector analysis

关于:checked伪类,最佳实践是配合<label></label>元素来实现,现在我们就通过:checked<label></label>元素来实现一个开关的效果。

示例代码如下:

nbsp;html>



  <meta>
  <meta>
  <meta>
  <title>开关</title>
  <style>
    [type="checkbox"] {
      width: 44px;
      height: 26px;
      position: absolute;
      opacity: 0;
      pointer-events: none;
    }

    /* 开关样式 */
    .cs-switch {
      display: inline-block;
      width: 44px;
      height: 26px;
      border: 2px solid;
      border-radius: 26px;
      background-color: currentColor;
      box-sizing: border-box;
      color: silver;
      transition: all .2s;
      cursor: pointer;
    }

    .cs-switch::before {
      content: "";
      display: block;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      background-color: #fff;
      transition: margin-left .2s;
    }


    :checked+.cs-switch {
      color: blueviolet;
    }

    /* 选中移动 */
    :checked+.cs-switch::before {
      margin-left: 18px;
    }

    /* 禁用状态 */
    :disabled+.cs-switch {
      opacity: .4;
      cursor: not-allowed;
    }
  </style>



  <!-- 普通状态 -->
  <input>
  <label></label>
  <!-- 选中状态 -->
  <input>
  <label></label>
  <!-- 禁用状态 -->
  <input>
  <label></label>
  <!-- 选中禁用状态 -->
  <input>
  <label></label>


Copy after login

运行效果如下所示:

css pseudo-selector learning pseudo-class selector analysis

5、逻辑组合伪类

:not()否定的伪类

    <li>

    优先级为0,优先级由括号中的表达式决定; :not(p)由p决定

    <li>

    可以不断的级联;
    input:not(:disabled):not(:read-only) {} ;表示处于不禁用,也不处于只读的状态

    <li>

    不可出现多个表达式,也不支持选择符;
    li:not(li, od); 尚未支持

:not()的巨大的用处在于告别重置的问题;

重置web中的样式,就好比我们在项目中经常使用到的:添加.active类名来控制样式的显示与隐藏/改变样式,往常的写法都是:

.cs_li {
	display: none;
}
.cs_li.active {
	display: block;
}
Copy after login

而我们可以使用:not()伪类,可以更好的实现:

.cs_li:not(.active) {
	display: none;
}
Copy after login

在列表中的设置<li>的边框时也可使用其:not()

.cs_li:not(:nth-of-type(5n)){
	margin-right: 10px; // 除5的倍数项都设置右边的外边距
}
Copy after login

:is()的作用是简化选择器

平时我们开发中经常会用到类似下面的语法:

.cs_li_a > img,
.cs_li_b > img,
.cs_li_c > img {
	display: none;
}
Copy after login

使用:is()简化可写成:

:is(.cs_li_a, .cs_li_b, .cs_li_c) > img {
	display: none;
}
Copy after login

还有一种嵌套之间的关系,相互嵌套,交叉组合得出结论;如下方所示

ol ol li,
ol ul li, 
ul ul li,
ul ol li {
	margin-left: 20px;
}
Copy after login

使用:is()伪类强化,则只需要几行代码:

:is(ol, ul) :is(ol, ul) li{
	margin-left: 20px;
}
Copy after login

<strong>:where()</strong>

:where()与上方的:is()相同,唯一不同的是级别永远为0,也不受括号里面的表达式影响;

使用的方法与:is()完全相同,但优先级永远是0;底下的括号中的优先级完全被忽略,俩句是同一个优先级,并且级别等同于.conten选择器

:where(.article, section) .conten {}
:where(#article, #section) .conten {
Copy after login

(学习视频分享:web前端入门

The above is the detailed content of css pseudo-selector learning pseudo-class selector analysis. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template