Libon

CSS Conditional Rules

14 分钟 #CSS
学习并掌握 CSS 条件规则,以及它们的用法与用途.

ToC

Is CSS Turing complete?

首先我们需要知道 CSS Conditional Rules 是什么东西。和字面意思一样,就是用于在 CSS 中做某些条件判断,就像其他编程语言中的 if 语句一样。大家都在说 CSS 不是一个编程语言,也包括我们一直在学习的教程里也是这么说,但你可能不知道,CSS 其实是一门 图灵完备 的语言,不过它并不是完整的,因为它还需要依赖于 HTML,所以“如果将用户交互视为 CSS ‘执行’ 的一部分”,那么 CSS + HTML 在创建布局这个方面上,它是图灵完备的。我在网上找到了一些能够证明这一观点的文章及一些仓库等,如果你有兴趣的话可以点击看看:

那什么是“图灵完备” ?宏观来讲,如果一个编程语言等价于 图灵机,那么它就是图灵完备的。图灵机是 Alan Turing 在 1936 年发明的,它称之为 “a-manchine”,也就是 ”自动机器“,而现代用于判断一门语言是否是图灵完备的条件则是使用了 Rule 110 规则,即:它是否可以完成 Rule 110 自动机。Rule 110 自动机简单来讲可以理解为它是否可以创建一个无限循环的状态机,详细的论证可以看一下 wiki 上的具体介绍。

关于图灵完备和 Rule 110 我们暂时先讲到这,以上内容只是为了证明在 CSS 中其实是存在着基本判断语句的,那么回到我们今天的主题,在 CSS 中,Conditional Rules 又是什么?

Conditional Rules

condition 即:条件,也就是我们日常编程中写的 if 语句或者是 ?: 三元表达式的那种条件。这个东西并不是空穴来风,也不是我的凭空捏造,它是确确实实存在的,证据如下:

在 MDN 中列举出了 4 条 rules ,它们分别是 @document @media @supports @import

@document

@docuemnt 目前只有 firefox 浏览器对其进行了实验性的支持,它的作用是如果当前的 url 和 @document url(<url>) 中的 <url> 进行匹配成功的话,那么其嵌套的样式就会生效。

1
@document url("https://www.example.com/") {
2
h1 {
3
color: green;
4
}
5
}

@media

@media 这个大家应该都用过,这是用于判断浏览器当前是否支持某种设备类型或是设备类型的某项参数是否符合要求的时候使用的,比如说 @media print 是用于判断当前是否是打印机预览的,@media (any-hover: hover) 是用于判断浏览器中是否支持触点设备进行 :hover 的,@media screen and (min-width: 900px) 是用于判断当前显示器的屏幕像素是否大于 900px 的,等等类似这些的判断还有很多,鉴于大家对此都较为熟悉,就不详细展开了。

@supports

@supports 则是用于判断浏览器是否支持某个特性的,比如在移动端 chrome、safari 浏览器在点击链接和按钮的时候会有一个背景高亮,正常情况下我们会使用 -webkit-tap-highlight-color: transparent 来将背景颜色设置为透明,但是它带有 -webkit- 前缀,不是一个标准的属性,意味着它不能在其他所有浏览器中正常工作,而在其他无法工作的浏览器中运行的话,会将这个属性作为无效属性处理,在 Edge 浏览器中的 development devtools 面板中会提示这个属性不是标准的,这可能会降低网站的评分,那么我们就可以使用 @supports 来解决这个问题:

1
@supports (-webkit-tap-highlight-color: transparent) {
2
a, [role="button"], button, input[type="button"] {
3
-webkit-tap-highlight-color: transparent;
4
}
5
}

同样的,在部分浏览器中支持 display 双值 的写法:display: block flow,同样可以使用 @supports 来进行检测判断:

1
@supports (display: block flow) {
2
.block-flow-box {
3
display: block flow;
4
}
5
}

最重要的是,它还可以通过判断 css variables 自定义属性,比如:

1
@supports (--display: true) {
2
.display-box {
3
display: block
4
}
5
}

当然这种用法只是一种抛砖引玉,真正要用时肯定不仅局限于此,我只是想用它来激发你产生更多的灵感而已。

@import

@import 这个方法咋一看会觉得它为什么也是 conditional rules ?但有些同学不知道的是它也是可以设置媒体查询的条件的,比如:

1
@import url("fineprint.css") print; // 在打印机打印的时候生效
2
@import url("bluish.css") projection, tv; // 在投影仪、或者大屏 tv 的时候生效
3
@import "common.css" screen, projection; // 在普通屏幕、投影仪设备上生效

More?

MDN 上收录的就只有这四个了,但其实还有很多可以实现这种类似的条件语句。比如说更为常见的 :empty :active :hover :focus :link :visited :first-child 等等其他关于元素状态的伪类,他们都是只有在特定场景下,某些条件符合的情况下才会生效的伪类,以下列出了一些比较常见的CSS伪类:

:activea:active选择活动的链接。
:checkedinput:checked选择被选中的 input 元素。
:disabledinput:disabled选择被禁用的 input 元素。
:emptyp:empty选择没有子元素的 p 元素。
:enabledinput:enabled选择已启用的 input 元素。
:first-childp:first-child选择其父级的首个子元素的 p 元素。
:first-of-typep:first-of-type选择其父级的首个 p 元素的 p 元素。
:focusinput:focus选择获得焦点的 input 元素。
:focus-withindiv:focut-within当子元素获取到焦点, 同时使用 :focus-within 的元素也可以获取焦点的时候生效。
:hovera:hover选择鼠标悬停其上的链接。
:in-rangeinput:in-range选择具有指定范围内的值的 input 元素。
:invalidinput:invalid选择所有具有无效值的 input 元素。
:lang(language)p:lang(it)选择 lang 属性值以 “it” 开头的 p 元素。
:last-childp:last-child选择其父级的最后一个子元素的 p 元素。
:last-of-typep:last-of-type选择其父级的最后一个 p 元素的 p 元素。
:linka:link选择所有未被访问的链接。
:not(selector):not(p)选择非 p 元素的元素。
:nth-child(n)p:nth-child(2)选择其父级的第二个子元素的 p 元素。
:nth-last-child(n)p:nth-last-child(2)选择作为父的第二个子元素的 p 元素,从最后一个子元素计数。
:nth-last-of-type(n)p:nth-last-of-type(2)选择作为父的第二个 p 元素的 p 元素,从最后一个子元素计数
:nth-of-type(n)p:nth-of-type(2)选择其父级的第二个 p 元素的 p 元素。
:only-of-typep:only-of-type选择其父级的唯一 p 元素的 p 元素。
:only-childp:only-child选择其父级的唯一子元素的 p 元素。
:optionalinput:optional选择不带 “required” 属性的 input 元素。
:out-of-rangeinput:out-of-range选择值在指定范围之外的 input 元素。
:read-onlyinput:read-only选择指定了 “readonly” 属性的 input 元素。
:read-writeinput:read-write选择不带 “readonly” 属性的 input 元素。
:requiredinput:required选择指定了 “required” 属性的 input 元素。
:rootroot选择元素的根元素。
:target#news:target选择当前活动的 #news 元素(单击包含该锚名称的 URL)。
:validinput:valid选择所有具有有效值的 input 元素。
:visiteda:visited选择所有已访问的链接。

但我们要聊的并不止这些。

@container

@container 是一个容器查询的条件规则,可以通过它来查询某个元素的尺寸大小、某些样式等,它内部的样式只有在容器查询对其元素的查询容器为 true 的时候才会进行匹配(生效).

1
<style>
2
body {
3
// 这条属性是必须的, 需要加在想要查询的父级元素上
4
// 它的值允许为 normal | size | inline-size
5
// https://www.w3.org/TR/css-contain-3/#container-type
6
container-type: size
7
8
}
9
11 collapsed lines
10
@container (min-width: 400px) {
11
div {
12
color: #f00
13
}
14
}
15
</style>
16
17
<div>
18
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Atque nesciunt accusantium ullam voluptate, laudantium rerum impedit tempora non
19
temporibus minima recusandae esse nemo praesentium, debitis voluptatibus ad officia, fugiat earum.
20
</div>

如果想要查询父级元素的样式是否符合某个值则可以使用 style() 来对 CSS 自定义属性进行匹配:

1
<style>
2
body {
3
// 使用样式查询的时候 container-name 属性是必须的
4
// 它的作用是给当前父容器起一个容器名称, 方便查询
5
container-name: body;
6
--featured: true; // 设置一个查询的值
7
--theme: dark;
8
}
9
18 collapsed lines
10
@container body style(--featured: true) {
11
div {
12
color: #f00
13
}
14
}
15
16
// 或者作为主题属性查询
17
@container body style(--theme: dark) {
18
div {
19
color: #fff
20
}
21
}
22
</style>
23
24
<div>
25
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Atque nesciunt accusantium ullam voluptate, laudantium rerum impedit tempora non
26
temporibus minima recusandae esse nemo praesentium, debitis voluptatibus ad officia, fugiat earum.
27
</div>

:has + :nth-last-child

以下的例子都需要将其组合起来才能看到效果。

从倒数第三个开始(包含倒数第三个),往上将所有的 li 的字体颜色设置为红色, 如果去掉 -last, 则会变成正数, 最后的结果是从正数第三个开始, 往下所有的 li 字体颜色都会变成红色

1
li:nth-last-child(n + 3) {
2
color: red;
3
}

如果子项小于5条, 那么会展示下边框, 如果多于5条则不会展示边框, 同时因为 display 不再为 list-item, 所以左侧的圆点也会消失, 效果如下

1
<style>
2
li {
3
border-bottom: 1px solid #000
4
}
5
6
li:nth-last-child(n + 5),
7
li:nth-last-child(n + 5)~li {
8
width: 50%;
9
display: inline-block;
18 collapsed lines
10
border-bottom: 0;
11
}
12
</style>
13
<ul>
14
<li><span>name: </span><span>1</span></li>
15
<li><span>name: </span><span>2</span></li>
16
<li><span>name: </span><span>3</span></li>
17
<li><span>name: </span><span>4</span></li>
18
</ul>
19
20
<ul>
21
<li><span>name: </span><span>1</span></li>
22
<li><span>name: </span><span>2</span></li>
23
<li><span>name: </span><span>3</span></li>
24
<li><span>name: </span><span>4</span></li>
25
<li><span>name: </span><span>5</span></li>
26
<li><span>name: </span><span>6</span></li>
27
</ul>

根据子元素的数量动态调整布局样式

1
<style>
2
.site-header__wrapper {
3
display: flex;
4
align-items: center;
5
gap: 1rem;
6
background-color: #f2ebff;
7
border-radius: 12px;
8
9
> * {
78 collapsed lines
10
flex: 1;
11
padding: 0.5rem 1rem;
12
}
13
}
14
15
.site-header__middle {
16
text-align: center;
17
18
a {
19
font-weight: bold;
20
}
21
}
22
23
.site-header__end {
24
display: flex;
25
justify-content: flex-end;
26
}
27
28
.c-nav {
29
display: flex;
30
gap: 0.5rem;
31
32
a {
33
display: block;
34
padding: 1rem 0.5rem;
35
}
36
}
37
38
.site-header__wrapper:has(li:nth-last-child(n + 4)) {
39
--layout-2: true;
40
}
41
42
@container style(--layout-2: true) {
43
.site-header__wrapper {
44
> * {
45
flex: initial;
46
}
47
}
48
49
.site-header__start {
50
order: 2;
51
}
52
53
.site-header__middle {
54
order: -1;
55
text-align: start;
56
}
57
58
.site-header__end {
59
margin-left: auto;
60
}
61
}
62
63
a {
64
text-decoration: none;
65
color: #222;
66
}
67
</style>
68
69
<header class="site-header">
70
<div class="wrapper site-header__wrapper">
71
<div class="site-header__start">
72
<button>Search</button>
73
</div>
74
<div class="site-header__middle">
75
<a href="#">Brand</a>
76
</div>
77
<div class="site-header__end">
78
<ul class="c-nav">
79
<li><a href="#">Home</a></li>
80
<li><a href="#">About</a></li>
81
<li><a href="#">Home</a></li>
82
<li><a href="#">Home</a></li>
83
<li><a href="#">Home</a></li>
84
</ul>
85
</div>
86
</div>
87
</header>

根据子元素的数量动态调整布局样式

1
<div class="modal">
2
<div class="modal__header">
3
<h2>Title to be added in here. It should be about two lines.</h2>
4
<button class="btn btn--icon" aria-label="Close">
5
<svg width="100pt" height="100pt" version="1.1" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
6
<path d="m50 43.57l-19.281-19.281c-1.7891-1.7852-4.6562-1.7773-6.4336-0.003906-1.7852 1.7891-1.7734 4.6562 0.003906 6.4336l19.281 19.281-19.281 19.281c-1.7852 1.7891-1.7773 4.6562-0.003906 6.4336 1.7891 1.7852 4.6562 1.7734 6.4336-0.003906l19.281-19.281 19.281 19.281c1.7891 1.7852 4.6562 1.7773 6.4336 0.003906 1.7852-1.7891 1.7734-4.6562-0.003906-6.4336l-19.281-19.281 19.281-19.281c1.7852-1.7891 1.7773-4.6562 0.003906-6.4336-1.7891-1.7852-4.6562-1.7734-6.4336 0.003906z" fill-rule="evenodd" />
7
</svg>
8
9
</button>
77 collapsed lines
10
</div>
11
<div class="modal__body">
12
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Perspiciatis harum odit repellat beatae dolore voluptate doloremque eaque in voluptatem similique tenetu.</p>
13
</div>
14
<div class="modal__footer">
15
<a href="#" class="btn">Ok, I understand</a>
16
</div>
17
</div>
18
19
<style lang="scss">
20
.modal {
21
display: flex;
22
flex-direction: column;
23
gap: 1rem;
24
max-width: 450px;
25
margin: 3rem auto;
26
padding: 1rem;
27
background-color: #eee7f8;
28
border-radius: 15px;
29
}
30
31
.modal__header {
32
display: flex;
33
align-items: flex-start;
34
gap: 1rem;
35
h2 {
36
font-weight: bold;
37
font-size: 1.5rem;
38
}
39
}
40
41
.btn {
42
display: inline-flex;
43
color: #fff;
44
background-color: #7f4fce;
45
padding: 0.5rem 1rem;
46
border-radius: 100px;
47
appearance: none;
48
border: 0;
49
font-size: 15px;
50
cursor: pointer;
51
border: 1px solid transparent;
52
}
53
54
.btn--ghost {
55
background-color: transparent;
56
color: #222;
57
border-color: rgba(#000, 0.15);
58
}
59
60
.btn--icon {
61
--size: 32px;
62
flex: 0 0 var(--size);
63
width: var(--size);
64
height: var(--size);
65
align-items: center;
66
justify-content: center;
67
padding: 0;
68
background-color: transparent;
69
70
svg {
71
fill: #797979;
72
width: var(--size);
73
height: var(--size);
74
}
75
}
76
77
.modal__footer {
78
display: flex;
79
justify-content: center;
80
gap: 0.5rem;
81
}
82
83
.modal__footer:has(a:nth-last-child(n + 2)) {
84
justify-content: flex-end;
85
}
86
</style>

根据子元素的数量动态调整布局样式

1
<div class="wrapper">
2
<div style="text-align: center; margin-bottom: 3rem;">
3
<button id="add">Add author</button>
4
<button id="remove">Remove author</button>
5
</div>
6
7
<div class="post-author" style="margin-bottom: 2rem;">
8
<h3>Written by:</h3>
9
<div class="post-author__wrapper">
81 collapsed lines
10
<div class="avatars-list">
11
<img class="avatar" src="https://xsgames.co/randomusers/avatar.php?g=male" alt="">
12
</div>
13
<p class="authors"><a href="#">Ahmad Shadeed</a></p>
14
</div>
15
</div>
16
</div>
17
18
<style lang="scss">
19
.post-author {
20
display: flex;
21
flex-flow: column wrap;
22
gap: 1rem;
23
24
h3 {
25
text-transform: uppercase;
26
font-size: 13px;
27
}
28
}
29
30
.post-author__wrapper {
31
display: flex;
32
flex-wrap: wrap;
33
align-items: center;
34
gap: 0.5rem;
35
36
a {
37
text-decoration: underline;
38
}
39
}
40
41
.post-author:has(img:nth-last-child(n + 2)) {
42
--multiple-avatars: true;
43
}
44
45
@container style(--multiple-avatars: true) {
46
.avatars-list {
47
display: flex;
48
background-color: #efefef;
49
padding: 8px 12px;
50
border-radius: 50px;
51
}
52
53
img:not(:first-child) {
54
border: solid 2px #fff;
55
margin-left: -0.25rem;
56
}
57
}
58
59
.avatars-list {
60
display: flex;
61
}
62
63
.avatar {
64
width: 40px;
65
height: 40px;
66
background-color: green;
67
border-radius: 50%;
68
69
@container style(--multiple-avatars: true) {
70
width: 30px;
71
height: 30px;
72
}
73
}
74
75
.wrapper {
76
max-width: 600px;
77
margin: auto;
78
padding: 1rem;
79
}
80
81
a {
82
text-decoration: none;
83
color: #222;
84
}
85
86
img {
87
display: inline-block;
88
object-fit: cover;
89
}
90
</style>

以上。


CD ..