简体   繁体   English

如何在div中垂直对齐div?

[英]How to vertically align a div within a div?

Horizontally aligning a div-element within another div-element can be achived with margin: 0 auto; 可以用margin: 0 auto;水平将一个div元素与另一个div元素对齐margin: 0 auto; as long as they both have a width-property other than auto , but this does not apply for vertical alignment. 只要它们都具有除auto以外的宽度属性,但这不适用于垂直对齐。

How can you vertically align a div within another div? 如何在另一个div中垂直对齐div?

There are a number of different approaches to this, based on various ideas. 基于各种想法,有很多不同的方法。 Given that the element has a fixed height (in px, % or what have you), the best solution I've found so far is based on the following principle: 鉴于元素具有固定的高度(以px,%或您所拥有的高度),到目前为止,我发现的最佳解决方案是基于以下原理:

Give the parent div position: relative; 给出父div position: relative; and the child div position: absolute; 子div position: absolute; , to make the child absolutley positioned in relation to the parent. ,以使孩子绝对相对于父母定位。

For the child, set top , bottom , left and right to 0 . 对于孩子,将topbottomleftright0 Given that the child also has a fixed width and height that is less than the size of the parent, this will push the browser into an impossible situation. 假设孩子的widthheight都小于父对象的大小,这将使浏览器陷入不可能的境地。

In comes margin: auto; margin: auto; on the child, as the browsers savior. 作为浏览器的救星。 The browser can now add enough margin on all sides to let the child-element keep its size, yet still fill out the entire parent as forced by top , bottom , left and right set to 0 . 现在,浏览器可以在所有面上添加足够的边距,以使子元素保持其大小,但仍需通过将topbottomleftright设置为0来强制填充整个父元素。

TADAAA! TADAAA! The element gets vertically and horizontally aligned within the parent. 元素在父级中垂直和水平对齐。

Markup 标记

<div class="parent">
    <div class="child"></div>
</div>

CSS 的CSS

​.parent {
    width: 200px;
    height: 200px;
    position: relative;
}

.child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
}

A working example 一个有效的例子

http://jsfiddle.net/sg3Gw/ http://jsfiddle.net/sg3Gw/

I find it easiest to use display:table-cell; vertical-align:middle; 我发现最容易使用display:table-cell; vertical-align:middle; display:table-cell; vertical-align:middle; here's a jsfiddle 这是一个jsfiddle

<style>
.a {
    border:1px solid red;
    width:400px;
    height:300px;
    display:table-cell;
    vertical-align:middle;
}
</style>
<div class="a">
    <div>CENTERED</div>
</div>
​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM