1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > css实现元素水平垂直居中

css实现元素水平垂直居中

时间:2022-10-30 00:16:31

相关推荐

css实现元素水平垂直居中

记录两个思路,当然还有其他方法,如果用到再补充:

<div class="parent" style="background:red;width:200px;height:100px;">

<div class="child" style="background:lightblue;">测试文字</div></div>

1.在伸缩容器上使用主轴对齐justify-content和侧轴对齐align-items

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

2.使用position:absolute;

(1)不考虑子元素和父元素的宽高

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

(2)子元素宽高固定



.parent{position: relative;}.child{position: absolute;top: 50%;left: 50%;width: 80px;height: 60px;margin-left: -40px;margin-top: -30px;}

3.text-align + line-height实现单行文本水平垂直居中

.test{text-align: center;line-height: 100px;

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