绝对定位元素的水平垂直居中
不知不觉,好几个月过去了,因为工作比较忙,最近才有空写笔记。呼呼,我不会忘了关注我的粉丝们~~~福利来了!!
正文开始:实现元素水平垂直居中的方法有很多,下面举例自己工作中比较常用的三中方法!
1.css实现居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width: 600px;
height: 400px;
position: absolute;
left: 50%; top: 50%;
border:1px solid #000;
background:red;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>明显不足的地方是:需要提前知道元素的宽度和高度。
2.css3实现水平垂直居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width: 600px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
border:1px solid #000;
background:red;
transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>无论元素的尺寸是多少,都可以居中。不过IE8以上才兼容这种写法,移动端可忽略
3.margin:auto实现居中,做项目的时候正好用的这种方法,很好使
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width: 600px;
height: 400px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
border:1px solid #000;
background:red;
margin: auto; /* 有了这个就自动居中了 */
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>来源于: http://www.qdfuns.com/notes/21738/93c9220f8fa40767833b80439291b1bd.html
本文作者: Jasmine
本文链接: https://www.jianbaizhan.com/article/524
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!