CSS :before 选择器
定义和说明
:before 选择器向选定的元素前插入内容。
使用content 属性来指定要插入的内容。
默认情况下,插入的内容是一个行内(内联)元素,但我们可以使用display属性改变其为块状元素。
语法:
:before {
style properties
}
如:
a[href]:before {content: "[LINK]";)
p:before {content: attr(class);}
浏览器支持
所有主流浏览器都支持:before选择器。
注意: before在IE8中运行,必须声明 <!DOCTYPE> 。
实例
1.CSS :before 选择器简单实例
每个 <p>元素之前插入内容:
p:before
{
content:"Read this: ";
}
2.css :before高级应用
(1)使用了css伪类元素before制作了一个自定义的input check样式。源代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn">
<head>
<title>CSS input checkbox自定义样式</title>
<style type="text/css">
.compare_button .checkboxcss {
cursor: pointer;
position: absolute;
width: 15px;
height: 15px;
top: 0;
left: 0;
background: #f7f7f7;
border: 2px solid #f5b34f;
border-radius: 5px;
}
.compare_button {
position: relative;
}
.compare_button .checkboxcss:before {
opacity: 0;
content: '';
position: absolute;
width: 7px;
height: 3px;
background: transparent;
top: 3px;
left: 3px;
border: 3px solid #1e8cc5;
border-top: none;
border-right: none;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.compare_button input[type=checkbox]:checked + label:before {
opacity: 1;
}
</style>
</head>
<body>
<div class="compare_button">
<input type="checkbox" id="compare_39680" class="checkbox-input">
<label class="checkboxcss" for="compare_39680"></label>
<span>compare text</span>
</div>
</body>
</html>
效果图:
(2)使用before伪类元素制作三角提示框
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>css before制作的边三角提示框</title>
<style type="text/css">
.arrow_box {
position: relative;
background: #88b7d5;
border: 1px solid #c2e1f5;
padding: 10px;
width: 200px;
height: 100px;
border-radius: 6px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
margin: 30px;
float: left;
}
.arrow_box::before{
position:absolute;
content:"";
height:0;
width: 0;
pointer-events: none;
border: solid transparent;
border-color: rgba(136, 183, 213, 0);
border-bottom-color: #88b7d5;
border-width: 10px;
left: 50%;
margin-left: -10px;
bottom: 100%;
}
</style>
</head>
<body>
<div class="arrow_box"></div>
</body>
</html>
效果图:
相关文章
CSS 教程: CSS伪元素
CSS 选择器参考手册: CSS :after 选择器