要论在前端面试中CSS常考的题目,程度垂直居中肯定有姓名。如果是平时不留神写款式的初学者,这道看似简略的问题也不是很容易答复,现整顿了一下CSS程度垂直居中的办法,可作为前端面试筹备材料。
要想做程度垂直居中,咱们先筹备两个盒子,大盒子外面套一个小盒子,这个时候咱们要想,套在外面的要做程度垂直居中的小盒子的宽高咱们晓得吗?宽高晓得或者不晓得,做程度垂直居中的办法一样吗?答案是不一样的,上面就要分状况探讨了,各提供了两种解决方案。
〇、先筹备一下盒子,也就是html的内容:
<div id="father1"> <div id="son1"> 程度垂直居中块级元素(已知宽高) </div> </div> <div id="father2"> <div id="son2"> 程度垂直居中块级元素(已知宽高) </div> </div> <div id="father3"> <div id="son3"> 程度垂直居中块级元素(未知宽高) </div> </div> <div id="father4"> <div id="son4"> 程度垂直居中块级元素(未知宽高) </div> </div>
一、已知小盒子宽高
办法1:子绝父相。子盒子的top、bottom、left、right为0,margin为auto
#father1{ width: 600px; height: 300px; position: relative; background-color: aquamarine; margin-bottom: 10px; } #son1{ position: absolute; width: 100px; height: 80px; top: 0; bottom: 0; left: 0; right: 0; margin: auto; background-color: beige; }
办法2:子绝父相。子盒子的top、left为50%,margin-top为负的子盒子高度的一半,margin-left为负的子盒子宽度的一半
#father2{ width: 600px; height: 300px; position: relative; background-color: blueviolet; margin-bottom: 10px; } #son2{ position: absolute; width: 100px; height: 80px; left: 50%; top: 50%; margin-left: -50px; /* #son2盒子宽度的一半的正数*/ margin-top: -40px; /* #son2盒子高度的一半的正数*/ background-color: chartreuse; }
二、未知小盒子宽高
办法1:子绝父相。子盒子的top、left为50% ,transform: translateX(-50%) translateY(-50%)
#father3{ width: 600px; height: 300px; background-color: coral; position: relative; margin-bottom: 10px; } #son3{ position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); background-color: cornsilk; }
办法2:弹性布局。设置justify-items和align-items为center
#father4{ width: 600px; height: 300px; display: flex; justify-content: center; align-items: center; background-color: darkred; } #son4{ background-color: darkgrey; }
【作者程度无限,欢送大家在评论区交换斧正~】