绝对定位实现单栏左右自适应上下自适应布局。这里的左右上下自适应布局是依赖于绝对定位的绝对定位的可视化格式模型的。下面就要介绍绝对定位在水平方向和垂直方向上各个参数之间的关系。
绝对定位元素的包含块?
在介绍正式内容之前,先介绍绝对定位即position为absolute元素的包含块。绝对定位元素的包含块是离他最近的position不为static元素的padding框区域,这个元素可以是行内元素或者块元素,具体详见:http://blog.youkuaiyun.com/wmaoshu/article/details/52981621。但一般情况下是块元素。
绝对定位的静态位置?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box {
position: relative;
width:200px;
height:200px;
padding:100px;
background-color: red;
}
.content {
width:100%;
height:100%;
background-color: #fff;
}
.abs {
position: absolute;
width:100px;
height:100px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<div class="abs"></div>
</div>
</div>
</body>
</html>
可能会不惊讶的问,绝对定位不是相对于包含快的padding区域定位的吗?黄块左上角应该应该位于红框中啊,为什么看起来像是相对于白框也就是外面这个box的内容区域定位的呢?其实在将要介绍的绝对定位可视化格式模型的规则中会发出现静态位置这一词语,所以要提前解析下这个词语。出现这个词语意味着:将绝对定位元素假设为position为realtive元素,相对的包含块是离他最近的快元素的content框构成。
水平方向各个元素之间的关系:
(1)当right和width和left部分为auto,先将margin-left和margin-right为auto的设置为0,然后执行如下过程:
(1)if(left和width为auto && right 不是 auto)宽度自适应,left公式求出。
(2)if(right和width为auto && left 不是 auto)宽度自适应,right公式求出。
(3)if(left和right为auto && width 不是 auto)left为静态位置值,right公式求出。
(4)if(其中之一为auto)公式求出。
用的最多的是(4)比如左右自适应比如 left:0 right:0
(2)当right和width和left都不为auto的话,margin-left和margin-right为auto,那么将会平分剩余空间,如果限制了会忽略left值。
垂直方向上各个元素之间的关系:
(1)当top和height和bottom部分为auto的话,会将margin-top和margin-bottom设置为0.然后执行如下过程:
1.if(top和height为auto && bottom不为auto) 高度内容决定 top公式求出
2.if(bottom和height为auto && top不为auto) 高度内容决定 bottom公式求出
3.if(top和bottom为auto && height不为auto) top静态位置决定 bottom公式求出
4.if(其中之一为auto) 直接由公式求出
(2)当top和height和bottom都不为auto的话,margin-top和margin-bottom为auto,那么将会平分剩余空间,如果限制了会忽略bottom值。
应用:
支付宝页面https://www.alipay.com/就是应用了这个技术进行布局的,代码是抽取出来的样子。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
/* 以下三个div的包含快不是main而是视口*/
.abs {
position: absolute;
left:0;
right:0;
/*宽度为自适应*/
}
</style>
<style>
* {
padding:0;
margin:0;
}
.header {
top:20px;
height:25px;
line-height: 25px;
z-index:100;
background-color: yellow;
}
.container {
top:0;
bottom:80px;
background-color: red;
}
.footer {
bottom:0;
height: 65px;
z-index: 100;
background-color: #333;
}
</style>
</head>
<body>
<div class="mian">
<div class="header abs">
</div>
<div class="container abs">
</div>
<div class="footer abs">
</div>
</div>
</body>
</html>
还可以实现一个元素的上下左右居中效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box {
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
width:100px;
height:100px;
margin:auto;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>