题目1:如何让一个子元素在父元素里水平垂直居中?
方法1
.box{400px;height:400px;background:#ccc;position:relative;}
.child{50px;height:50px;position: absolute;left:50%;top:50%;margin-left:-25px;margin-top:-25px;background:red;}
<div class="box">
<div class="child"></div>
</div>
方法2:
.box{400px;height:400px;background:#ccc;position:relative;}
.child{50px;height:50px;margin:auto;overflow:auto;position: absolute;left:0;top:0;right:0;bottom:0;background:blue;}
<div class="box">
<div class="child"></div>
</div>
方法3:
.box{400px;height:400px;background:#ccc;position:relative;}
.child{50px;height:50px;margin:auto;position: absolute;left:50%;top:50%;transform:translate(-50%,-50%);-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);background:pink;}
<div class="box">
<div class="child"></div>
</div>
方法4:
.box{400px;height:400px;background:#ccc;display: table-cell;text-align: center;vertical-align: middle;}
.child{50px;height:50px;display:inline-block;background:red;}
<div class="box">
<div class="child"></div>
</div>
方法5:
.box{400px;height:400px;background:#ccc;display: flex;justify-content:center;align-items:center;}
.child{50px;height:50px;background:red;}
<div class="box">
<div class="child"></div>
</div>
题目2:高度已知,分为三栏,左右各300px,中间自适应?
方法1:浮动布局
.box>div{height:100px;}
.box .left{300px;background:red;}
.box .center{background:pink;}
.box .right{300px;background:blue;}
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">中间栏:浮动布局</div>
</div>
方法2:定位布局
.box{position:relative;}
.box>div{height:100px;position:absolute;}
.box .left{left:0;top:0;300px;background:red;}
.box .center{left:300px;top:0;right:300px;background:pink;}
.box .right{top:0;right:0;300px;background:blue;}
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">中间栏:定位布局</div>
</div>
方法3:flex布局
.box{display: flex;}
.box>div{height:100px;position:absolute;}
.box .left{300px;background:red;}
.box .center{flex:1;background:pink;}
.box .right{300px;background:blue;}
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">中间栏:flex布局</div>
</div>
方法4:表格布局
.box{display: table; 100%;}
.box>div{display: table-cell;height:100px;}
.box .left{300px;background:red;}
.box .center{background:pink;}
.box .right{300px;background:blue;}
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">中间栏:table布局</div>
</div>
方法5:网格布局
.box{display: grid;grid-template-rows:100px;grid-template-columns:300px auto 300px;}
.box>div{height:100px;}
.box .left{background:red;}
.box .center{background:pink;}
.box .right{background:blue;}
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">中间栏:grid布局</div>
</div>
本人正在不断地学习摸索中,如有错误,欢迎指正,如有不同的解题思路也欢迎指教~