意外的 CSS 重置

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 $200 免费信用额度!

在 CSS 中使用简写属性时,您会设置所有与它相关的属性所有值。这不是错误,只是 CSS 的工作方式。我曾多次看到它让人感到困惑。让我们揭示这个问题,希望让它更容易理解。

以下是一个示例

.module {
  background-repeat: no-repeat;
  background: url(lion.jpg);
  /* Oops! This will repeat. */
}

简写 CSS background 属性会覆盖所有子属性。background-repeat 的默认值为 repeat,因此在简写中未声明它时,它将被设置为该默认值。

对于每个背景子属性,它都以这种方式工作

.module {
  /* This will get set to `repeat` */
  background-repeat: no-repeat;

  /* This will get set to `0 0` */
  background-position: top right;

  /* This will get set to `auto auto` */
  background-size: 100px;

  /* This will get set to `scroll` */
  background-attachment: fixed;

  /* This will get set to `border-box` */
  background-origin: content-box;

  /* This will get set to `border-box` */
  background-clip: padding-box;

  /* This will get set to `transparent` */
  background-color: red;

  /* This will get overridden */
  background-image: url(cool.png);

  /* OVERRIDE */
  background: url(lion.jpg);
}

对于盒子模型(及相关)内容,情况也是如此,例如

.module {
  margin-right: 20px;
  margin: 10px;
  /* margin-right will be 10px now */

  padding-top: 30px;
  padding: 10px;
  /* padding-top will be 10px now */

  border-left: 1px;
  border: 0;
  /* border-left will be removed */
}

字体是另一个您可能会意外重置自己的情况

p {
  /* Will get reset to what is set in shorthand (required) */
  font-family: Sans-Serif;

  /* Will get reset to what is set in shorthand (required) */
  font-size: 24px;
  
  /* Will get reset to `normal` */
  line-height: 2;

  /* Will get reset to `normal` */
  font-style: italic;

  /* will get reset to `normal` */
  font-weight: bold;

  /* will get reset to `normal` */
  font-variant: small-caps;

  /* OVERRIDE */
  font: 16px Serif;
}

请注意,简写至少需要 font-family 和 font-size 才能工作。

列表是另一个

ul {
  /* Will get reset to what is set in shorthand */
  list-style-type: square;
 
  /* Will get reset to `outside` */
  list-style-position: inside;

  /* Will get reset to `none` */
  list-style-image: url(cooldot.png);

  /* OVERRIDE */
  list-style: disc;
}

flexbox 布局中的 flex 属性也是简写

.flex >  span {
  /* Will be reset to `auto` (or `main-size` if supported) */
  flex-basis: 150px;

  /* Will be reset to `1` */
  flex-grow: 0;

  /* Will be reset to `1` */
  flex-shrink: 0;

  /* OVERRIDE */
  flex: auto;
}

不过,这是一个不寻常的情况,因为简写不仅重置了您可能不希望重置的内容,而且以您可能希望重置但可能不知道的方式重置了它们。 Fantasai

我们(Flexbox 规范编辑)强烈建议不要使用 'flex' 的长格式,除非您真的非常希望从其他样式规则级联 flex 设置,因此我建议以某种方式阻止使用 'flex-grow/shrink/basis'(或者,最好是将其省略或放在高级部分)。简写以适当的方式重置内容,因此将导致更少的级联错误。请使用简写!


这是一个 Pen,其中包含一些实际代码中的这些内容。