目录
一、使用子绝父相实现垂直居中
二、使用margin+transform来实现垂直居中
三、使用flex布局实现垂直居中
一、使用子绝父相
父元素位于相对定位,子元素绝对定位,再结合transform的水平和垂直移动来实现不定宽高的子元素垂直居中
HTML:
<div class="parent">父元素<div class="child">子元素</div></div>
SCSS:
.parent {width: 400px;height: 400px;background-color: rgb(223, 252, 144);position: relative;.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%); //基于自身的宽度移动width: 200px;height: 200px;background-color: rgb(57, 192, 255);}}
二、使用margin+transform
SCSS:
.parent {width: 400px;height: 400px;background-color: rgb(223, 252, 144);.child {margin: 0 auto;transform: translateY(50%); //基于自身的宽度移动width: 200px;height: 200px;background-color: rgb(57, 192, 255);}}
三、使用flex布局
SCSS:
.parent {width: 400px;height: 400px;background-color: rgb(223, 252, 144);display: flex;align-items: center;justify-content: center;.child {width: 200px;height: 200px;background-color: rgb(57, 192, 255);}}