css:before和after中的content属性

css有一个属性叫做content。content只能使用在:after和:before之中。它用于在元素之前或者元素之后加上一些内容

就像这样:

.email-address:before {
   content: "Email address: ";
}

我们可以书写的html代码:

<ul>
   <li class="email-address">chriscoyier@gmail.com</li>
</ul>

输出的内容是这样的:

• Email address: chriscoyier@gmail.com

让我们细致的看看这个属性:

使用特殊的字符:

我们可以借鉴表格来判断特殊的ASCII码对应的字符,表格点击我! 就像表格中展示的一样,版权的图标© 是 &#169; 所以ASCII 是169.

然后点击表格进行css以及js中使用的字符数字之间的转换。


简单但是很实用,下面是一些简单的字符:

0A9 - 版权
2192 - 右箭头
2190 - 左箭头

使用属性

你可以在content中使用目标元素的属性,例如一个链接可能如下:

<a title="A web design community." href="http://css-tricks.com">CSS-Tricks</a>

你可以获取上面链接的title属性:

a:before {
   content: attr(title) ": ";
}

我们可以使用目标元素的任何属性,只要只用了形式是 attr(name-of-attribute)的写法

#Example Trick: CSS3 tooltips

a {
  color: #900;
  text-decoration: none;
}

a:hover {
  color: red;
  position: relative;
}

a[title]:hover:after {
  content: attr(title);
  padding: 4px 8px;
  color: #333;
  position: absolute;
  left: 0; 
  top: 100%;
  white-space: nowrap; 
  z-index: 20px;
  -moz-border-radius: 5px; 
  -webkit-border-radius: 5px;  
  border-radius: 5px;  
  -moz-box-shadow: 0px 0px 4px #222;  
  -webkit-box-shadow: 0px 0px 4px #222;  
  box-shadow: 0px 0px 4px #222;  
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);  
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
  background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);  
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);  
  background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);  
  background-image: -o-linear-gradient(top, #eeeeee, #cccccc);  
}

因为所有的元素都有title属性,所以可以使用data-自定义属性这样子来对于制定特性的元素设置样式。

需要考虑的点:

  • Firebug不能检测目标元素。在  WebKit 的浏览器中可以指检测到元素,但是,不能展现目标元素的健对值。 
  • 不能用于变形和动画属性。

浏览器支持

所有的主流浏览器(Firefox 3+, Safari 3+, Chrome 3+, Opera 10+, and Internet Explorer 8+) (查看表格) 支持 :after/:before。

原文地址:https://www.cnblogs.com/RachelChen/p/5535339.html