文章转载自:div盒子水平垂直居中的方法 - 雪明瑶
这个问题比较老,方法比较多,各有优劣,着情使用。
一、盒子没有固定的宽和高
方案1、Transforms 变形
这是最简单的方法,不仅能实现绝对居中同样的效果,也支持联合可变高度方式使用。内容块定义transform: translate(-50%,-50%) 必须加上
top: 50%; left: 50%;
优点:
1. 内容可变高度
2. 代码量少
缺点:
1. IE8不支持
2. 属性需要写浏览器厂商前缀
3. 可能干扰其他transform效果
4. 某些情形下会出现文本或元素边界渲染模糊的现象
<div class="wrapper">我不知道我的宽度和高是多少,我要实现水平垂直居中。</div>
.wrapper { padding: 20px; background: orange; color: #fff; position: absolute; top: 50%; left: 50%; border-radius: 5px; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%); }
方案二2、在父级元素上面加上上面3句话,就可以实现子元素水平垂直居中。
<div class="wrapper"> 我不知道我的宽度和高是多少,我要实现水平垂直居中。 </div>
.wrapper {
500px;
height: 300px;
background: orange;
color: #fff;
/*只需要在父元素上加这三句*/
justify-content: center; /*子元素水平居中*/
align-items: center; /*子元素垂直居中*/
display: -webkit-flex;
}
二、盒子有固定的宽和高
方案1、margin 负间距
此方案代码关键点:1.必需知道该div的宽度和高度,
2.然后设置位置为绝对位置,
3.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,
4.最后将该div分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。
<div class="wrapper">我知道我的宽度和高是多少,我要实现水平垂直居中。</div>
.wrapper { width: 400px; height: 18px; padding: 20px; background: orange; color: #fff; position: absolute; top:50%; left:50%; margin-top: -9px; margin-left: -200px; }
方案2、margin:auto实现绝对定位元素的居中(该方法兼容ie8以上浏览器)
此方案代码关键点:1、上下左右均0位置定位;
2、margin: auto;
<div class="wrapper">我不知道我的宽度和高是多少,我要实现水平垂直居中。</div>
.wrapper { width: 400px; height: 18px; padding:20px; background: orange; color: #fff;position</span>:<span style="color: #0000ff;"> absolute</span>;<span style="color: #ff0000;"> left</span>:<span style="color: #0000ff;">0</span>;<span style="color: #ff0000;"> right</span>:<span style="color: #0000ff;">0</span>;<span style="color: #ff0000;"> top</span>:<span style="color: #0000ff;"> 0</span>;<span style="color: #ff0000;"> bottom</span>:<span style="color: #0000ff;"> 0</span>;<span style="color: #ff0000;"> margin</span>:<span style="color: #0000ff;"> auto</span>; }</pre>
C/C++ IAT HOOK MessageBoxW
C/C++ HOOK 全局 API
c/c++创建静态库
如何画Windows窗体
WindowsPE TLS表
WindowsPE 延迟加载导入表
WindowsPE 资源表
WindowsPE 重定位表
WindowsPE 导出表
- 最新文章
-
使用 CSS 在不影响视觉效果的情况下增大元素的点击面积
mysql 用grant 新建用户指定同一个网段主机的方法
为Ubuntu新创建用户创建默认.bashrc并解决ubuntu20.04 命令行没有颜色的问题
【问题解决】Ubuntu中Python3升级高版本后 Err returned non-zero status 1 或者status 2问题解决
Python3学习笔记
解决apt-get /var/lib/dpkg/lock-frontend 问题
使用Go env命令设置Go的环境
go: cannot use path@version syntax in GOPATH mode
b0105 大数据集群-2021分布式A(手动3节点)-环境搭建
b0104 大数据集群-2021伪分布式-环境搭建
