css实现未知高度水平垂直居中

时间:2024-01-10 17:22:50

页面设计中,经常需要实现元素的水平垂直居中,css实现的方法有很多(列如: margin: auto、position定位、css表达式calc()、使用css预处理、table等都可以实现水平居中),但大多都是针对容器高度不固定,元素高度固定的情况。

这里我们介绍几种实现容器宽高和元素宽高都不固定的情况实现水平垂直居中

github代码片段地址: https://github.com/haozhaohang/library/tree/master/%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%ADdemo

一、flex实现水平垂直居中

 <!DOCTYPE html>
<html>
<head>
<title>实现未知高度的垂直居中</title> <style>
html, body {
height: 100%;
} .containers {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style> </head>
<body>
<div class="containers">
<span>flex实现垂直居中</span>
</div>
</body>
</html>

容器设置display: flex;

容器内的元素设置 jusify-content: center;实现水平居中

        align-items: center; 实现垂直居中

二、grid实现水平垂直居中(这可能是实现水平垂直居中最简单的css样式)

 <!DOCTYPE html>
<html>
<head>
<title>实现未知高度的垂直居中</title> <style>
html, body {
height: 100%;
} .containers {
height: 100%;
display: grid;
} span {
margin: auto;
}
</style> </head>
<body>
<div class="containers">
<span>grid实现垂直居中(许这是最简洁的水平垂直居中的 CSS 样式)</span>
</div>
</body>
</html>

目前浏览器的支持率,但是可以用在内部的管理系统,在指定的浏览器上运行

容器设置 display: grid;

容器元素设置 margin: auto; 实现水平垂直居中