一、前言
标准流布局
正常我们看到的所有的网页标签都在标准流的布局中,也就是看到的标签都是从上到下,从左到右排列的。
脱离标准流布局
有时候我们想要某个工具栏或者某个自定义的div层
悬浮在浏览器的上下左右位置(或者网页的任何位置),这个图层不会随着网页的滚动而移出它固定在屏幕的那个位置范围,这个时候这个div层
其实已经脱离了标准流布局了。那么脱离标准流有几种方式呢,两种:
- float属性
- position属性搭配left/right/top/bottom属性
二、float属性
float属性让子标签浮动在父标签的左边和右边。有两个取值:left/right,代码样式和效果如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Float浮动-脱离标准流</title>
<style>
#main{
background-color: red;
width: 500px;
height: 200px;
color: white;
}
.test1{
background-color: blue;
float: left;
width: 150px;
height: 60px;
}
.test2{
background-color: orange;
float: right;
}
.test3{
background-color: purple;
}
</style>
</head>
<body>
<div id="main">
<div class="test1">浮动父标签左边</div>
<div class="test2">浮动父标签右边</div>
<div class="test3">未浮动的子标签</div>
</div>
</body>
</html>
![](https://img.haomeiwen.com/i301530/63d41e20f88216a5.png)
PS:任何标签只要一浮动,类型就会被转为行内-块级标签。
三、position定位属性
position可以让子标签在父标签的任意位置进行定位。默认值为static
,要浮动定位时设置子标签为absolute
,父标签为relative
,简称子绝父相。PS:任何标签只要设置position属性,类型就会被转为行内-块级标签。下面是position的属性:
![](https://img.haomeiwen.com/i301530/88eb856c0afb8b97.png)
- absolute:绝对定位,自己的位置根据父标签体系中最后一个值为static的父标签进行定位。
- relative:相对定位,相对于正常位置进行定位。
- fixed:相对于浏览器窗口进行定位。一般用于让标签粘着浏览器的上下左右位置。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Position定位-脱离标准流</title>
<style>
*{
margin:0;
}
div.test1{
background-color: red;
height: 50px;
position: fixed;
top:0;
width: 50%;
}
div.test2{
margin:100px;
width: 200px;
height: 150px;
background-color: greenyellow;
position: relative;
}
div.test3{
width: 100px;
height: 40px;
background-color: purple;
position: absolute;
left: 0;
bottom:0;
}
</style>
</head>
<body>
<div class="test1">定位到浏览器的顶部</div>
<div class="test2">
<div class="test3">position定位</div>
</div>
</body>
</html>
![](https://img.haomeiwen.com/i301530/e8759dc6a9aa7484.png)
四、总结
float属性和position属性区别
- float属性:只可以浮动在父标签的左边或右边。设置float属性的标签还是跟父标签中的其他标签有关系,比如说,父标签的下一个子标签还是会相对于它的左上角进行定位。
- position定位:可以在任何位置浮动定位。设置position属性的标签脱离了标准了,其他任何标签不受它影响。
最后,如果有什么问题欢迎向我指出,谢谢。
网友评论