1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > CSS不定宽高垂直水平居中的方法

CSS不定宽高垂直水平居中的方法

时间:2023-11-03 08:55:22

相关推荐

CSS不定宽高垂直水平居中的方法

目录

一、使用子绝父相实现垂直居中

二、使用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);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。