html固定中心,css 两边固定中间自适应布局的实现
解析四種常用方法以及原理:浮動、浮動內(nèi)嵌 div、定位、flex。
浮動
.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; }
我在左邊
我在右邊
我排最后,但是跑到中間來了
原理:
浮動元素和非浮動元素不在同一個立體空間,如果不清浮動,位置在它下面的元素將往上浮。
浮動元素高度為0,浮動盒子層級比 block 塊級水平盒子高,比 inline/inline-block 水平盒子低。
浮動內(nèi)嵌 div
.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;
}
我在中間
我在左邊
我在右邊
原理:
三個元素都浮動,其中主題元素沾滿一行 100% ,利用負 margin 把左右兩邊的元素放好。
主題元素里面再套一個子元素,子元素 margin: 0 200px ,防止內(nèi)容跑到左右兩塊浮動元素下面被遮蓋。
定位
.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;}
我在中間,我用 margin 抵消左右兩塊定位元素占據(jù)空間
我在左邊,我是定位元素
我在右邊,我是定位元素
原理:
左右兩個元素定位,可放任意位置。
中間元素用 margin: 0 200px,防止內(nèi)容跑到左右兩塊定位元素下面被遮蓋。
flex
.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;}
我在左邊
我在中間,flex: 1 自動占據(jù)剩余空間
我在右邊
原理:
flex 布局,子元素默認水平排列。
flex: 0 1 auto -> 默認,占據(jù)空間不跟隨父級放大,跟隨變小,自身本來寬度
flex: 1 1 auto -> auto,占據(jù)空間跟隨父級放大,同時跟隨變小,自身本來寬度
flex: 0 0 auto -> none,占據(jù)空間不跟隨父級放大,同時也不跟隨變小,自身本來寬度
flex: 1 1 1 -> auto,占據(jù)空間跟隨父級放大,同時跟隨變小,并且自動占滿剩余空間
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持免費資源網(wǎng)。
總結(jié)
以上是生活随笔為你收集整理的html固定中心,css 两边固定中间自适应布局的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android双进程守护耗电,Andro
- 下一篇: android开发计算器微积分,不到1M