将 <div> 居中的最佳方式在垂直和水平页面上? [英] Best way to center a <div> on a page vertically and horizontally?
问题描述
在页面上垂直和水平居中
我知道 margin-left: auto;margin-right: auto;
将在水平方向上居中,但垂直方向的最佳方法是什么?
最好最灵活的方式
这个演示的主要技巧是在元素从上到下的正常流动中,所以 margin-top: auto
设置为零.但是,绝对定位元素对于自由空间的分配作用相同,同样可以在指定的top
和bottom
垂直居中(在IE7中不起作用).
##这个技巧适用于任何尺寸的div
.
div {宽度:100px;高度:100px;背景颜色:红色;位置:绝对;顶部:0;底部:0;左:0;右:0;保证金:自动;}
<div></div>
Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
The best and most flexible way
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto
is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top
and bottom
(does not work in IE7).
##This trick will work with any sizes of div
.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
这篇关于将 <div> 居中的最佳方式在垂直和水平页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!