CSS 控制对齐 align
- 参考
- 《 OReilly.CSS.Secrets.2015.6 》
水平居中
for inline element
for block element
垂直居中,big show!
absolute positioning solution
- 缺点: this technique is that it requires fixed dimensions
1
2
3
4 | <main>
<h1>Am I centered yet?</h1>
<p>Center me, please!</p>
</main>
|
1
2
3
4
5
6
7
8
9 | main {
position: absolute;
top: 50%;
left: 50%;
margin-top: -3em; /* 6/2 = 3 */
margin-left: -9em; /* 18/2 = 9 */
width: 18em;
height: 6em;
}
|
1
2
3
4
5
6 | main {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
|
有些 browser 可能会有些模糊,加上 transform-style: preserve-3d
试试,这是 hacky 方法。
viewport unit solution
如果要避免使用 absolute positioning
1
2
3
4
5
6 | main {
width: 18em;
padding: 1em 1.5em;
margin: 50% auto 0;
transform: translateY(-50%);
}
|
对齐到 View Port,vh,vw 是基于 view port 的单位,1vh = 1% view height,参见 http://w3.org/TR/css-values-3/#viewport-relative-lengths
1
2
3
4
5
6 | main {
width: 18em;
padding: 1em 1.5em;
margin: 50vh auto 0;
transform: translateY(-50%);
}
|
Flexbox solution
专业选手,只是老浏览器支持不好!
- parent element 设置 ` display: flex`
- 目标 element 设置
margin: auto;
例如:
1
2
3
4
5
6
7
8 | body {
display: flex;
min-height: 100vh;
margin: 0;
}
main {
margin: auto;
}
|
如果要居中目标 element 的内容,可以设置 flex 相关 property
1
2
3
4
5
6
7 | main {
display: flex;
align-items: center;
justify-content: center;
width: 18em;
height: 10em;
}
|
table layout method & inline-block method
http://css-tricks.com/centering-in-the-unknown