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中使用的字符數字之間的轉換。


簡單但是很實用,下面是一些簡單的字符:

\00A9 - 版權
\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。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM