文档流
所谓文档流就是按照元素的顺序从左到右、由上而下的方式排列。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
img{
width:400px;
height: 100px;
}
</style>
<body>
<img />
<img />
<img />
<img />
<img />
<img />
<img />
</body>
</html>
定位
默认的文档流很多时候不能满足我们的布局要求,需要更丰富的布局手段,这就需要用到定位了。
定位方式有:static、fixed、relative、absolute。
static 静态定位(默认)
无定位,元素正常出现了流(文档流)中,不受left、right、top、bottom属性的影响。
relative 相对定位
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
div{
width: 200px;
height: 200px;
}
.div1{
background-color: green;
}
.div2{
position: relative;
background-color: yellow;
left: 50px;
bottom: 100px;
}
.div3{
background-color: red;
}
</style>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
</html>
显示效果:
absolute 绝对定位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
div{
width: 200px;
height: 200px;
border: 1px black solid;
position: relative;
}
#div21{
background-color: green;
}
#div22{
background-color: yellow;
position: absolute;
top:20px;
left:30px;
}
#div23{
background-color: red;
}
</style>
<body>
<div id="div1"></div>
<div id="div2">
<div id="div21"></div>
<div id="div22"></div>
<div id="div23"></div>
</div>
</body>
</html>
显示效果:
fixed固定定位
将上例中div22的绝对定位(absolute)改成固定定位(fixed),显示效果如下:
z-index
重新定位之后可能会出现重叠,通过z-index可以调整其顺序。z-index默认值为auto,即与父元素相同,可以设置为数值,数值大的层位于相对小的上方。
上例中div1被div22覆盖了,如果将div1的z-index设置为1(大于div22,其默认为auto)
#div1{
background-color: orange;
z-index: 1;
}
定位总结
(1)标准文档流按照从左到右、自上而下的方式依次排列元素。若要改变默认布局方式则需使用relative、absolute、fixed等定位方式;
(2)relative是相对于其原有位置进行偏移;
(3)absolute是相对于其父容器进行偏移,注意其父容器必须是有定位的,即非默认(static)定位方式,否则会一直往上追溯,直到页面;
(4)fixed是相对于整个页面进行偏移
浮动
通过设定浮动(float),可以使得元素从原本的文档流中脱离出来,感觉像浮在原本的文档流上面
案例:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>浮动案例</title>
</head>
<style>
.div1{
width: 624px;
height: 626px;
background-color: #86d0ea;
position: relative;
}
.div2{
position: absolute;
width: 624px;
height: 376px;
top: 124px;
background-color: #c0c0c0;
}
.div3{
width: 376px;
height: 376px;
background-color: #adff2f;
float: left;
margin-left: 125px;
}
</style>
<body>
<div class="div1"></div>
<div class="div2">
<div class="div3"></div>
</div>
</body>
</html>