让子元素在父元素中水平居中垂直居中的方法
方法1:写一个伪元素,将它设置为行内块元素,高度与父元素相同,写一条属性,vertical-align:middle,子元素也要写,具体代码如下:
<style>
div{width:500px;height:500px;box-shadow:0 0 5px #000; text-align:center;}
.zi{width:100px;height:100px;background:#60C;display:inline-block;vertical-align:middle;}
div:after{content:""; height:500px; background:#00C;display:inline-block;vertical-align:middle;}
</style>
</head>
<body>
<div >
<div class="son"></div>
</div>
方法2:利用定位,给大的div写一个position:relative;子元素写position:absolute; 这时子元素的包含块就是外面大的div,然后给里面的div写一下位置left:0;right:0;top:0;bottom:0;margin:auto;主要看一下CSS中的样式,具体代码如下:
div{width:500px;height:500px;box-shadow:0 0 5px #000; position:relative;}
.son{width:100px;height:100px;background:#60C; position:absolute; left:0;right:0;top:0;bottom:0;margin:auto;}
方法3:这种方法是在前一种方法上的延申,只是不是用margin,而是使用transform:translate()可以在不知道宽高的情况下进行居中,tranlate()函数是相对于自身的。
具体代码如下:
div{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.son{width:100px;height:100px;background:#60C;position:absolute;left:50%;top:50%;transform:translate(-50px,-50px);}
方法4:使用弹性盒,给父元素设置这三条属性display:flex; 水平方向居中 justify-content:center;垂直方向居中align-items:center;具体代码如下:
div{width:500px;height:500px;box-shadow:0 0 5px #000; display:flex; justify-content:center;align-items:center;}
.son{width:100px;height:100px;background:#60C;}