解析四種常用方法以及原理:浮動、浮動內嵌 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>
原理:
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>
原理:
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,占據空間跟隨父級放大,同時跟隨變小,并且自動占滿剩余空間以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答