217 - 《CSS 技巧》

发布于 2022年11月21日

1、使用 unset 重置所有属性。

button { all: unset }

2、:not 使用技巧。

/* 实现间隔线 */
li:not(:last-child) { border-right: 1px solid #ccc; }
/* 实现文本以 , 分割 */
li:not(:last-child)::after { content: "," }
/* 给有 href 但没有 class 属性的 a 增加样式,适用于 CMS */
a[href]:not([class]) { color: #008000; }

3、优先使用本地字体以提升性能。

@font-face {
  font-family: "Dank Mono";
  src:
    /* Full name */
    local("Dank Mono"),
    /* Postscript name */
    local("Dank-Mono"),
    /* Otherwise, download it! */
    url("//...a.server/fonts/DankMono.woff");
}
code {
  font-family: "Dank Mono", system-ui-monospace;
}

4、垂直居中技巧两则。

html,
body {
  height: 100%;
  margin: 0;
}
body {
  align-items: center;
  justify-content: center;
  display: flex;
}

或者

body {
  display: grid;
  place-items: center;
  height: 100vh;
  margin: 0;
}

5、用负的 nth-child 选择前几项。

li { display: none; }
/* 显示前 3 项 */
li:nth-child(-n+3) { display: block; }
/* 显示除前 3 以外的项 */
li:not(:nth-child(-n+3)) { display: block; }

6、用「猫头鹰」选择器选择非首项元素

/* 选择兄弟节点,但不包含第一项 */
* + * { margin-top: 1.5em; }
/* 我理解等同于 */
*:not(:first-child) { margin-top: 1.5em; }
/* 不显示多余的 br */
br + br { display: none; }

7、使用 flex 的 space-between 去除多余外边距

.list {
  display: flex;
  justify-content: space-between;
}
.list .perso

内容预览已结束

此内容需要会员权限。请先登录以查看完整内容。