絕對定位實(shí)現(xiàn)雙列布局
1. 前言
無論什么布局幾乎都可以使用絕對定位來實(shí)現(xiàn),那為什么好多布局并不會首選絕對定位呢?
一方面是因?yàn)閷懫饋砜赡苡悬c(diǎn)麻煩,另一方面是因?yàn)楸仨毜?code>算,那具體要怎么算
呢?
看來實(shí)現(xiàn)你就明白了。
2. 實(shí)例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 清除默認(rèn)樣式 */
* { padding: 0; margin: 0; }
/* 令html和body全屏顯示, 并有一個灰色背景 */
html, body { height: 100%; background: gray; }
/* 在父元素上設(shè)置相對定位 */
body { position: relative; }
div {
/* 絕對定位 */
position: absolute;
/* 令其上下方向與父元素的距離為0 */
top: 0;
bottom: 0;
/* 白色背景 */
background: white;
}
/* 左邊的列 */
.left {
/* 令其左側(cè)方向與父元素的距離為2% */
left: 2%;
/* 令其右側(cè)方向與父元素的距離為51% */
right: 51%;
}
/* 右邊的列 */
.right {
/* 令其左側(cè)方向與父元素的距離為51% */
left: 51%;
/* 令其右側(cè)方向與父元素的距離為2% */
right: 2%;
}
</style>
</head>
<body>
<div class="left"></div>
<div class="right"></div>
</body>
</html>
運(yùn)行結(jié)果:
3. 小結(jié)
這里加起來不等于 100%,因?yàn)檫@里的百分號指的不是寬度,而是相對于父元素的距離。
那這該怎么算呢?其實(shí)也簡單,我們在屏幕正中央位置畫一條線,這條線就代表距離左邊 50%、距離右邊也是 50%:
然后左邊 2%、右邊 2%、中間 2%,但是中間的 2% 被平分成了兩個 1%,我們再畫幾條線看一下:
左邊的紅線代表 left: 2%;,右邊的兩條綠線加在一起就是 51%,代表 right: 51%;
其實(shí)就是一道簡單的數(shù)學(xué)題,算好百分比就可以用絕對定位啦!