首页 技术 正文
技术 2022年11月17日
0 收藏 781 点赞 3,595 浏览 1001 个字

页面设计中,经常需要实现元素的水平垂直居中,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; 实现水平垂直居中

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903