首发于Html+Css

CSS中的::after ::before与原理详解

前言

今天来说一下这俩个伪类元素,因为用的不多,感觉这俩个东西已经快被遗忘了。

概念

::before 选择器向选定的元素前插入内容。
使用 content 属性来指定要插入的内容。

::after 选择器在被选元素的内容后面插入内容。
使用 content 属性来指定要插入的内容。

before 前增

<style type="text/css">
	span::before{
		content: '我是前增';
	}
</style>

<body>
	<span><--前增</span>
</body>

after 后增

<style type="text/css">
	span::after{
		content: '我是后增';
	}
</style>

<body>
	<span>后增--></span>
</body>

after 和 before 多是用来清除浮动的,再说这个的时候顺便把原理也讲了

我们先来看一段清除浮动的代码:

<style type="text/css">
	.box{
		margin: 200px auto;
		width: 400px;
		background: #42B983;
		border: 3px solid #000000;
	}
	
	.chl_box{
		width: 200px;
		height: 200px;
		background: #00FFFF;
		float: left;
	}
</style>

<body>
	<div class="box">
		<div class="chl_box"></div>
                <!-- height: 0;overflow: hidden; 为了解决 IE 浏览器的兼容问题 -->
		<div style="height: 0;overflow: hidden;clear: both;"></div>
	</div>
</body>

在早期我们通过在div标签中添加了一个空的标签,并且给这个空的标签清除浮动。但是这样的话就需要每次都添加一个空的标签。再来看下面这段通过 after 来清除浮动的代码

<style type="text/css">
	.box{
		margin: 200px auto;
		width: 400px;
		background: #42B983;
		border: 3px solid #000000;
	}
	
	.chl_box{
		width: 200px;
		height: 200px;
		background: #00FFFF;
		float: left;
	}
	
	.box::after{
		content: "";
		display: block;
                clear: both;
                /* height: 0;overflow: hidden; 为了解决 IE 浏览器的兼容问题 */
 		height: 0;
		overflow: hidden;
                /* visibility:hidden;为了去隐藏content中的内容 */
		visibility: hidden;
	}
</style>

<body>
	<div class="box">
		<div class="chl_box"></div>
	</div>
</body>

从效果上来看,after和before也是一个标签,所以我们就可以利用这个伪元素来清除浮动,从根本上来说它和加一个空标签来清除浮动是一样的。这也是他的原理

编辑于 2020-11-10 17:17