blog
blog copied to clipboard
元素垂直居中的几种实现——2018年12月23号
元素居中的几种实现
阅读时间1m 35s
#技术笔记
一 . 居中是一个常见的考试题通常有下面两个形式
- 已知宽高的垂直左右居中
- 未知宽高的垂直左右居中
已知一个元素的宽高做垂直居中
.element {
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
这种写法兼容性强,好理解,但,::这种方法有一个很明显的不足,就是需要提前知道元素的尺寸::。否则margin负值的调整无法精确。此时,往往要借助JS获得。
未知宽高做垂直居中
CSS3中有一个属性是transform属性 他有一个叫translate的值
translate()指定对象的2D translation(2D平移)。第一个参数对应X轴,第二个参数对应Y轴。如果第二个参数未提供,则默认值为0
偏移的百分比值是相对于自身大小的,无论绝对定位元素的尺寸是多少,其都是水平垂直居中显示的。
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
::问题很明显,兼容性不好 IE10+以及其他现代浏览器才支持::
还有一种非常诡异的写法
.element {
width: 600px; height: 400px;
position: absolute; left: 0; top: 0; right: 0; bottom: 0;
margin: auto;
}
::两个关键点:上下左右均0位置定位;margin: auto::
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>垂直居中</title>
<style>
.main {
width: 300px; height:300px;
position: relative;
border: 1px solid saddlebrown;
}
.box {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
width: 200px; height: 100px;
margin: auto;
border: 1px red solid;
}
</style>
</head>
<body>
<div class="main">
<div class="box"></div>
</div>
</body>
</html>
.element { width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
}
这种方法除了兼容性,还有个东西需要考虑:
当元素最终宽高为奇数
时,元素上面的文字偶尔
会模糊,原因尚未知。