解析四種經常使用方法以及原理:浮動、浮動內嵌 div、定位、flex。css
<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>
原理:html
block
塊級水平盒子高,比 inline/inline-block
水平盒子低。<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>
原理:flex
margin: 0 200px
,防止內容跑到左右兩塊定位元素下面被遮蓋。<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>
原理:spa
flex
佈局,子元素默認水平排列。flex: 0 1 auto
-> 默認,佔據空間不跟隨父級放大,跟隨變小,自身原本寬度flex: 1 1 auto
-> auto,佔據空間跟隨父級放大,同時跟隨變小,自身原本寬度flex: 0 0 auto
-> none,佔據空間不跟隨父級放大,同時也不跟隨變小,自身原本寬度flex: 1 1 1
-> auto,佔據空間跟隨父級放大,同時跟隨變小,而且自動佔滿剩餘空間