CSS 垂直对齐表格单元格不适用于绝对位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8896965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:41:19  来源:igfitidea点击:

Vertical align table-cell don't work with position absolute

cssvertical-alignmentcss-tables

提问by Jens T?rnell

http://jsfiddle.net/fQv97/

http://jsfiddle.net/fQv97/

HTML

HTML

<div class="table-cell">
    My text, should be align middle
</div>

CSS

CSS

.table-cell {
    height: 200px;
    width: 200px;
    vertical-align: middle;
    background: #eee;
    display: table-cell;
    position: absolute;
}

Problem

问题

The text should be placed in the middle of my "table cell". Everything works as expected until I add "position: absolute". Now it can't place my content in the middle any more? Why not? It still knows my height and width because I set it in my CSS.

文本应该放在我的“表格单元格”的中间。一切都按预期工作,直到我添加“位置:绝对”。现在它不能再将我的内容放在中间了吗?为什么不?它仍然知道我的高度和宽度,因为我在 CSS 中设置了它。

Any clever workaround for this?

有什么聪明的解决方法吗?

回答by thirtydot

Everything works as expected until I add "position: absolute". Now it can't place my content in the middle any more? Why not?

一切都按预期工作,直到我添加“位置:绝对”。现在它不能再将我的内容放在中间了吗?为什么不?

position: absoluteforces display: block, read number two here.

position: absolute部队display: block在这里读第二点。

As for a workaround, I think you'll have to wrap it in another element:

至于解决方法,我认为您必须将其包装在另一个元素中:

<div class="table-cell-wrapper">
    <div class="table-cell">
        My text, should be align middle
    </div>
</div>

.table-cell-wrapper {
    position: absolute;
}
.table-cell {
    height: 200px;
    width: 200px;
    vertical-align: middle;
    background: #eee;
    display: table-cell;
}

回答by Matt K

There are some workarounds I've discovered for this, such as adding a hash before position:

我为此发现了一些解决方法,例如在位置之前添加哈希:

#position: absolute;

That hack was found here: Vertical Centering in CSS

在这里找到了这个技巧:CSS 中的垂直居中

回答by FlashTrava

here is the solution:

这是解决方案:

<div style="position: absolute; /*your position*/">
    <div class="table-cell">
        My text, should be align middle
    </div>
</div>