解析四種常用方法以及原理:浮動、浮動內嵌 div、定位、flex。
浮動
<style type="text/css">
.wrap {background: #eee; padding: 20px; }
p {margin: 0; }
.left {width: 200px; height: 200px; float: left; background: coral; }
.right {width: 200px; height: 200px; float: right; background: lightblue; }
.middle {margin: 0 200px; background: lightpink; }
</style>
<div class="wrap">
<p class="left">我在左邊</p>
<p class="right">我在右邊</p>
<p class="middle">我排最後,但是跑到中間來了</p>
</div>
原理:
- 浮動元素和非浮動元素不在同一個立體空間,如果不清浮動,位置在它下面的元素將往上浮。
- 浮動元素高度爲0,浮動盒子層級比
block
塊級水平盒子高,比inline/inline-block
水平盒子低。
浮動內嵌 div
<style type="text/css">
.wrap {background: #eee; padding: 20px; }
p {margin: 0; }
.left {width: 200px; height: 200px; float: left; background: coral; margin-left: -100%;}
.right {width: 200px; height: 200px; float: left; background: lightblue; margin-left: -200px;}
.middle {width: 100%; height: 200px;float: left; background: lightpink; }
span{
display: inline-block;
margin: 0 200px;
}
</style>
<div class="wrap">
<p class="middle">
<span class="inner">
我在中間
</span>
</p>
<p class="left">我在左邊</p>
<p class="right">我在右邊</p>
</div>
原理:
- 三個元素都浮動,其中主題元素沾滿一行 100% ,利用負
margin
把左右兩邊的元素放好。 - 主題元素裏面再套一個子元素,子元素
margin: 0 200px
,防止內容跑到左右兩塊浮動元素下面被遮蓋。
定位
<style type="text/css">
.wrap {background: #eee; position: relative;}
p {margin: 0; }
.left {width: 200px; height: 200px; background: coral; position: absolute;left: 0; top: 0;}
.right {width: 200px; height: 200px; background: lightblue; position: absolute;right: 0; top: 0;}
.middle {height: 200px; background: lightpink; margin: 0 200px;}
</style>
<div class="wrap">
<p class="middle">我在中間,我用 margin 抵消左右兩塊定位元素佔據空間</p>
<p class="left">我在左邊,我是定位元素</p>
<p class="right">我在右邊,我是定位元素</p>
</div>
原理:
- 左右兩個元素定位,可放任意位置。
- 中間元素用
margin: 0 200px
,防止內容跑到左右兩塊定位元素下面被遮蓋。
flex
<style type="text/css">
.wrap {background: #eee; display: flex}
p {margin: 0; }
.left {width: 200px; height: 200px; background: coral; }
.right {width: 200px; height: 200px; background: lightblue; }
.middle {height: 200px; background: lightpink; flex: 1;}
</style>
<div class="wrap">
<p class="left">我在左邊</p>
<p class="middle">我在中間,flex: 1 自動佔據剩餘空間</p>
<p class="right">我在右邊</p>
</div>
原理:
-
flex
佈局,子元素默認水平排列。 -
flex: 0 1 auto
-> 默認,佔據空間不跟隨父級放大,跟隨變小,自身本來寬度 -
flex: 1 1 auto
-> auto,佔據空間跟隨父級放大,同時跟隨變小,自身本來寬度 -
flex: 0 0 auto
-> none,佔據空間不跟隨父級放大,同時也不跟隨變小,自身本來寬度 -
flex: 1 1 1
-> auto,佔據空間跟隨父級放大,同時跟隨變小,並且自動佔滿剩餘空間