html将元素垂直水平居中的方式
将元素垂直,水平居中分两种情况:一个是元素尺寸固定,二是元素尺寸不固定
1)margin负间距
必须知道居中盒的宽度和高度;
为居中盒设置绝对定位;
距离定位父级左边框和上边框的距离设置为50%;
将元素分别左移和上移,移动元素宽度和高度的一半
2)margin: auto;实现绝对定位元素的居中
必须知道居中盒的宽度和高度;
为居中盒设置绝对定位;
分别设置left: 0; right: 0; top: 0; bottom: 0;
为居中盒设置margin: auto;
图解
方法1:尺寸固定
方法1:定位 ,50%,margin负距
.box{
width: 400px;
height: 300px;
border: 2px solid black;
/* 把元素变成定位元素 */
position: absolute;
/* 元素距离上,左都为50% */
left: 50%;
top: 50%;
/* 让元素的左外边距,上外边距为元素宽高的1/2 注意margin是负距*/
margin-top: -150px;
margin-left: -200px;
}
方法2:四方为都为0 ,margin:auto
.box{
width: 400px;
height: 300px;
border: 2px solid black;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
方法3:元素尺寸不固定
.box2 {
position: absolute;
left: 50%;
top: 50%;
/* 设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)*/
transform: translate(-50%, -50%);
}
方法四:使用伪元素
利用inline-block与vertical-align配合伪元素达到垂直居中
/* 背景左右居中 */
.dialog_container {
text-align: center;
position: absolute;
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.35);
}
/* 伪元素上下居中 */
.dialog_container:after {
display: inline-block;
width: 0;
height: 100%;
content: "";
vertical-align: middle;
}
/* 真正居中的元素 */
.dialog_box {
display: inline-block;
vertical-align: middle;
text-align: left;
border: 1px solid black;
}
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634342.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现