css技巧收集

时间:2023-03-09 21:55:53
css技巧收集

1. 使用 :not() 为导航添加/取消边框

传统的方法为导航栏添加边框:

/* add border */
.nav li {
      border-right: 1px solid #666;
}

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

用css的:not()实现:

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

减少了很多代码实现了相同的功能。

2. 垂直居中(任何元素)

html, body {
      height: 100%;
      margin: 0;
}

/*要设置垂直居中的元素*/
element {
      -webkit-align-items: center;
      -ms-flex-align: center;
      align-items: center;
      display: -webkit-flex;
      display: flex;
}

3. 使用负的 nth-child 选取元素

使用负的 nth-child 在 1 到 n 之间选择元素:

li {
  display: none;
}
/* 使用负的 nth-child 在 1 到 n 之间的元素,选择第1到3个元素就是nth-child(-n+3) */
li:nth-child(-n+3) {
      display: block;
}使用 :not()来做:
li:not(:nth-child(-n+3)) {
    display: none;
}
 

4. 使用 Flexbox 来避免 Margin Hacks

在做多列布局的时候,可以通过 Flexbox 的 space-between 属性来避免nth-first-、 last-child 等 hacks:

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

.list .person {
      flex-basis: 23%;
}

这样,列之间的空白就会被均匀的填满。