欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浮动与绝对定位脱离文档流的区别

程序员文章站 2024-01-28 21:41:22
...

浮动脱离文档流

先看代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style>
	*{
		margin:0;
		padding:0;
		list-style: none;
	}
	.wrap{
		height: 200px;
		width: 200px;
		background-color: red;
		float: left;
	}
	.test{
		height: 100px;
		background-color: #ccc;
	}
	
</style>
<body>
	<div class="wrap"></div>
	<div class="test">this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,</div>
</body>
</html>

效果

浮动与绝对定位脱离文档流的区别

结论:

对于使用float:left而浮动的元素,其他盒子会无视它,从浏览器左上角开始布局,而盒子内的文本依旧会为浮动的元素让出位置

可以从上图看出,文本的盒子其实是从左上角布局的,但是文本,是从红色结束才开始布局



绝对定位脱离文档流

代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style>
	*{
		margin:0;
		padding:0;
		list-style: none;
	}
	.wrap{
		height: 200px;
		width: 200px;
		background-color: red;
		position: absolute;
	}
	.test{
		height: 100px;
		background-color: #ccc;
	}
</style>
<body>
	<div class="wrap"></div>
	<div class="test">this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,this is a test,</div>
</body>
</html>

效果:

浮动与绝对定位脱离文档流的区别

 

结论:

从上图可以看出,使用绝对定位的元素,其他盒子会忽视它,而其他盒子内的文本同样也会忽视它,从左上角开始布局