面试题:垂直居中几种方法

一、使用定位

方法1.

top和left分别为50%,在使用margin-left和margin-top设置负的宽高(图片也可以使用)

条件:这种方法必须设置子盒子的宽高

.father{ height:300px; width:600px; background:yellow; overflow:hidden;}

.child {boder: 1px black solid; background:white; text-aligin:center; width:100px; height:50px;}

.father {position: relative;}

.child {position:absolute; top:50%; left:50%; margin-top:-25px; margin-left:-50px;}         

方法2:

top right bottom left 都设置为0 再使用margin:auto(图片也可)

条件:父盒子必须设置宽高,子盒子不必须

.father {height:300px; width:600px; background:yellow; overflow:hidden;}

.child {border:1px black solid; bakcground:white; text-align:center;}

.father{position:relative;}

.child{ position:absolute; top:0; left:0; right:0;bottom:0; margin:auto}

方法3:

top和left分别为50%,再使用transform:translate(-50%,-50%)(图片也可以用这种方式)

条件:子盒子不需要设置宽高,缺点是兼容性不好

.father {position:relative;}

.child {position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);}

二、弹性盒子

方法1

设置主轴和交叉轴都居中,支持不同屏幕大小(图片也可以)

条件:兼容性不好

.father { display :flex; justify-content:center; align-items:center;}

方法2

.father {display :flex;} 

.child{margin:auto}

三、使用display:table-cell

本来用于文本的垂直居中,可以将div设置为inline(图片也可以)

.father {display:table-cell; text-align:center; vertical-align:middle;}

posted @ 2020-07-23 11:55  啾啾啾c  阅读(343)  评论(0编辑  收藏  举报