如何垂直对齐到具有定义的宽度/高度的div的内容的中心?

如何垂直对齐到具有定义的宽度/高度的div的内容的中心?

问题描述:

在定义的宽度/高度 div 中垂直居中任何内容的正确方法是什么。

What would be the correct method to vertically center any content in a defined width/height div.

示例中,有两个不同高度的内容,使用类垂直居中的最佳方法是什么, .content 。 (它适用于每个浏览器,没有 table-cell 的解决方案)

In the example there are two contents with different heights, what is the best way to center vertically both using the class .content . (and it works for every browser and without the solution of table-cell)

有一些解决方案,但是想知道其他的想法,一个是使用 position:absolute; top:0;底部:0; margin auto

Have some solutions on mind, but would like to know other ideas, one is using position:absolute; top:0; bottom: 0; and margin auto.

我已经研究了这一点,从我发现你有四个选项:

I have researched this a little and from what I have found you have four options:

如果您不介意在父div上使用 display:table-cell ,则可以使用以下选项:

If you do not mind using the display:table-cell on your parent div, you can use of the following options:

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:table-cell;
    vertical-align:middle;
}​

Live DEMO

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:block;
}

.content {
    height: 100px;
    width: 100px;
    display:table-cell;
    vertical-align:middle;    
}​

Live DEMO

.area{
    background: red;
    margin:10px;
    text-align: center;
    display:block;
    float: left;
}

.content {
    display:table-cell;
    vertical-align:middle;
    height: 100px;
    width: 100px;
}​

Live DEMO

我使用这个版本的唯一问题是,似乎你必须为每个具体的实现创建css。这样做的原因是内容div需要具有您的文本将填充的设置高度,并且margin-top将被计算出来。这个问题可以在演示中看到。您可以通过更改内容div的高度%并将其乘以-5以获取您的margin-top值,让其适用于每个场景。

The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.

.area{
    position:relative; 
    display:block;
    height:100px;
    width:100px;
    border:1px solid black;
    background:red;
    margin:10px;
}

.content { 
    position:absolute;
    top:50%; 
    height:50%; 
    width:100px;
    margin-top:-25%;
    text-align:center;
}​

现场DEMO