css :before选择器介绍

css :before选择器用于向被选元素前面插入指定内容,一般情况下,:before选择器要和content属性一起使用,设置在对象前(依据对象树的逻辑结构)发生的内容。

默认情况下,插入的内容是一个行内(内联)元素,但我们可以使用display属性改变其为块状元素。

语法:

:before { 
   style properties 
}

如:

a[href]:before  {content: \"[ ]\";) 
p:before {content: attr(class);} 

 

css :before选择器简单实例

向每个 <p>元素之前插入内容:

<!DOCTYPE html>
<html>
<head>
<style>
p:before
{
content:\"Read this -\";
}
</style>
</head>
<body>
<p>My name is Donald</p>
<p>I live in Ducksburg</p>
<p><b>Note:</b> For :before to work in IE8, a DOCTYPE must be declared.</p>
</body>
</html>

在线运行

 

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  ns=\"http://www.w3.org/1999/xhtml\"  :lang=\"zh-cn\">
<head>
< >CSS input checkbox自定义样式</ >
<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>

效果图:

\"CSS

 

2、使用before伪类元素制作三角提示框

<html  ns=\"http://www.w3.org/1999/xhtml\" >
<head>
    < >css before制作的边三角提示框</ >
    <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

收藏 打印