CSS 插入生成内容

187 阅读1分钟

CSS 中定义了生成内容的方式,这样的内容通过 CSS 插入,而不通过标记或内容表示。 例如:列表标记。书写列表的时候,并没有任何内容是表示记号的,记号是浏览器自动生成的。无序列表记号是某种符号;有序列表记号默认是递增的数字。

指定生成的内容

插入生成内容之前,必须以某种方式指定生成什么内容,此时就需要用到content属性

content: normal(默认) | string | url | counter | attr | open-quote | close-quote
  | no-open-quote | no-close-quote | inherit;

插入生成内容

生成内容通过伪元素(一般为::before ::after)插入到文档中,如:

a[href]::before {
  content: '(link) ';
}

a[href]::after {
  content: attr(href);
}

题外话:before 和 after 的限制

  • ::before ::after选择符的目标是块级元素,那么display属性的值只能为noneinlineblock。其他的值都会当做block
  • 如果它们的目标是行内元素,那么display的属性值只能为noneinline。其他值都当做inline

现在看一下 clear 清除浮动的方式:

.clearfix::after {
  content: '';
  display: table;
  clear: both;
}
.clearfix {
  *zoom: 1;
}

其中的display: table并没有什么特殊的用意,其实就等同于display: block