HTML清除浮动最优方式

原理:利用:after和:before来在元素内部插入两个元素块,从而达到清除浮动的效果。其实现原理类似于clear:both方法,只是区别在于:clear在html中插入一个div.clear标签,而outer利用其伪类clear:after在元素内部增加一个类似于div.clear的效果。

            .clearfloat {
				zoom: 1;/*为了兼容性,因为ie6/7不能使用伪类,所以加上此行代码。*/
			}
			
			
			.clearfloat:after {
				display: block;/*首先要显示伪元素,所以display:block,*/
				clear: both;/*要清除浮动,所以,clear:both。*/
				content: "";/*content 属性与 :before 及 :after 伪元素配合使用,来插入生成内容。*/
				visibility: hidden;/*作用是允许浏览器渲染它,但是不显示出来,这样才能实现清除浮动。 */
				height: 0;/*为使伪元素不影响页面布局,将伪元素高度设置为0*/
			}
			
			.div1 {
				background: white;
				border: 1px solid red;
			}
			
			.div2 {
				background: #800080;
				border: 1px solid red;
				height: 100px;
				margin-top: 10px
			}
			
			.left {
				float: left;
				width: 20%;
				height: 200px;
				background: #DDD
			}
			
			.right {
				float: right;
				width: 30%;
				height: 80px;
				background: #DDD
			}

正文

    <body>
		<div class="div1 clearfloat">
			<div class="left">Left</div>
			<div class="right">Right</div>
		</div>
		<div class="div2 clearfloat">
			div2
		</div>
	</body>

效果图

猜你喜欢

转载自blog.csdn.net/qq_36925536/article/details/85600822
今日推荐