块级元素居中方案

1. 方案一

html:

1
<div class="main"></main>

css:

1
2
3
4
5
6
7
8
9
10
.main{
width:400px;
height:200px;
background:#eee;
position:absolute;
left:50%;
top:50%;
margin-left:-200px;
margin-top:-100px;
}

利用定位,移动宽高的一半,然后margin负值回去一半的一半。

2.方案二

html:

1
<div class="main"></div>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
body {
height: 100%;
}
.main{
width: 400px;
height: 200px;
background:#eee;
position:absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}

最常用,直接一个布局搞定,在水平方向垂直方向都可以自定义的居中。

3.方案三

html:

1
2
3
<div class="main">
hello world
</div>

css:

1
2
3
4
5
6
7
.main{
background:#eee;
position:absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}

这个其实和第一个非常类似,他们是做了一个位移,位移的方位分别是 x 和 y 两个轴上。移动自身的 50% 注意这个地方位移不是指外部容器的 50% 而是自身。

Stack Overflow中的解释

4.方案四

html:

1
2
3
4
<body>
<div class="main">
</div>
</body>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
html,body{
width: 100%;
height: 100%;
display: -webkit-flex;
display: flex;
justify-content:center;
align-items:center;
}
.container{
width: 400px;
height: 200px;
background: #ccc;
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2015 - 2021 昨夜凛雨 All Rights Reserved.

UV : | PV :