tk挠痒痒网址发布页-秘密武器
历史搜索

css 垂直居中常用的方法

游客2025-05-16 08:11:01

如何将一个未知高度的元素垂直居中,通常有两种常用的方法:

//html
<div >
   <div >center</div>
</div>

1、用绝对定位和translate

.parent{
   height: 300px;
   width: 300px;
   position: relative;
   background-color: bisque;
}
.child{
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   padding: 30px;
   background-color: cornflowerblue;
}

2、基于 Flexbox 的解决方案

这是毋庸置疑的最佳解决方案,因为 Flexbox 是专门针对这类需求所设计的,只是一些老的浏览器版本兼容性可能不是很好,具体可以查看caniuse,现代浏览器一般没问题。

.parent{
   height: 300px;
   width: 300px;
   background-color: bisque;
   display: flex;
   justify-content: center;
   align-items: center;
}
.child{
   padding: 30px;
   background-color: cornflowerblue;
}

css 垂直居中常用的方法 1

标签:CSS

本文是由用户"游客"发布,所有内容的版权归原作者所有。没有经过书面许可,任何单位或个人不得以任何形式复制、转载、引用本网站的内容。否则将追究法律责任。

相关专题