絕對定位實現單欄左右自適應上下自適應佈局。這裏的左右上下自適應佈局是依賴於絕對定位的絕對定位的可視化格式模型的。下面就要介紹絕對定位在水平方向和垂直方向上各個參數之間的關係。
絕對定位元素的包含塊?
在介紹正式內容之前,先介紹絕對定位即position爲absolute元素的包含塊。絕對定位元素的包含塊是離他最近的position不爲static元素的padding框區域,這個元素可以是行內元素或者塊元素,具體詳見:http://blog.csdn.net/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>