CSS 技巧

使用 :not 伪类设置不同选项

Multi-column

推荐写法

.nav li:not(:last-child) {
  border-right: 1px solid #ccc;
}

不推荐写法

.nav li {
  border-right: 1px solid #ccc;
}

.nav li:last-child {
  border-right: none;
}

使用 CSS 变量

Multi-column

推荐写法

:root {
  --blue: #1e90ff;
  --white: #fff;
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
}

不推荐写法

body {
  background-color: #1e90ff;
}

h2 {
  border-bottom: 2px solid #1e90ff;
}

.container {
  color: #1e90ff;
  background-color: #fff;
}

使用复合属性

Multi-column

推荐写法

.article-container {
  padding: 10px 15px 20px 15px;
  border: 1px solid black;
}

不推荐写法

.article-container {
  padding-top: 10px;
  padding-right: 15px;
  padding-bottom: 20px;
  padding-left: 15px;

  border-width: 1px;
  border-style: solid;
  border-color: black;
}

使用短横线/语义化命名

Multi-column

推荐写法

.nav-item {
  /* ... */
}

.contact-form {
  /* ... */
}

.article-paragragh {
  /* ... */
}

不推荐写法

.p {
  /* ... */
}

.myFirstForm {
  /* ... */
}

使用群组选择器

Multi-column

推荐写法

.main li,
.main li a {
  color: red;
}

不推荐写法

.main li {
  color: red;
}

.main li a {
  color: red;
}

使用相对单位代替绝对单位

Multi-column

推荐写法

body {
  font-size: 16px;
}

p {
  font-size: 1rem;
  line-height: 1.25;
  margin-bottom: 0.5em;
}

不推荐写法

p {
  font-size: 16px;
  line-height: 20px;
  margin-bottom: 8px;
}

重置样式

Multi-column

推荐写法

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

不推荐写法

h1 {
  margin: 0;
  padding: 0;
}

a {
  margin: 0;
}