TailwindCSS 很好用,我用上瘾了,但写的时候补全总会出现一些没见过的样式命名,所以我去重新看了文档,整理了一下。
我把他的样式分成两类,一是简单语句,二是复合语句,比如 top-0
这种就是简单语句,因为他控制的就是 top
样式,而复合语句,我对他的定义是一条语句能操作多个不同类的 CSS 样式,且命名方式不按 CSS 规律,比如 truncate
。
复合语句能有效减少代码量,可能短短几个字母就能把一大串简单语句的功能覆盖。
由于 tailwind 的文档中没有单独把他们归类,所以本文主要会列出我能找到的所有复合语句进行介绍。
truncate
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
就是文字过长显示省略号的“简写”,在父元素宽度确定的前提下,一句就能取代 overflow-hidden text-ellipsis whitespace-nowrap
。
divide-x/y
& > :not(:last-child) {
border-inline-start-width: 0px;
border-inline-end-width: 1px;
}
& > :not(:last-child) {
border-top-width: 0px;
border-bottom-width: 1px;
}
效果是给多个元素之间加上分隔线,分隔线是通过 border
实现的。
因为是 border
所以最好用在元素之间没有间隔的场景,在带有 gap
场景不适用,毕竟这种时候你还得手动设置元素的 padding
调整边界与元素之间的距离。
divide-solid/dotted/dashed 与 divide-(color)
& > :not(:last-child) {
border-style: solid;
}
是配合 divide-x/y
使用的,看样式就知道 divide-x/y
只是设置了 border
的宽度,连 border
的 color
、style
都没有定义,所以需要用额外的 divide
语句去描述。
space-x/y 与 space-x/y-reverse
& > :not(:last-child) {
--tw-space-x-reverse: 0;
margin-inline-start: calc(calc(var(--spacing) * <number>) * var(--tw-space-x-reverse));
margin-inline-end: calc(calc(var(--spacing) * <number>) * calc(1 - var(--tw-space-x-reverse)));
};
和 divide
类似,但用途相反,这个是基于 margin
的复合语句,用在元素之间需要间隔的场景,通过 margin
将元素之间分隔开。
space-x/y-reverse
是 space-x/y
的补丁,在元素反向排列的场景下,就应该一起用。
以只使用 space-x
为例,他会给每个元素(非最后一个)的右侧加上 margin
,如 1(空)2(空)3
,但在 flex-reverse
的情况下,就会变成 32(空)1(空)
,space-x/y-reverse
就是修复这种情况的。
sr-only 与 not-sr-only
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
position: static;
width: auto;
height: auto;
padding: 0;
margin: 0;
overflow: visible;
clip: auto;
white-space: normal;
可能是接触比较少的功能了,sr-only
用于定义某些元素只能在屏幕阅读器上查看,在普通屏幕上看不到,not-sr-only
则反过来。
size-*
width: *;
height: *;
用于给 width
和 height
设置同一个值,比如 size-full
就是宽高均为 100%。
line-clamp
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: <number>;
和 truncate
类似,line-clamp
就是设置显示多少行后省略,整合了一套模版写法。
ring
--tw-ring-shadow: 0 0 0 1px;
ring
是 outline
的一种替代,以 box-shadow
实现,两者都能设置 offset,但 ring
在环和元素的中间可以设置颜色,而 outline
不行,只能是透明的。