[英]display:table-cell doesn't work properly with 100% width
I wanted to align text vertically inside of div
: 我想在
div
内垂直对齐文本:
display:table-cell;
vertical-align: middle;
Text is getting aligned, but div
(which has 100% width) becomes smaller in width. 文本已对齐,但是
div
(宽度为100%)的宽度变小。 What is the problem? 问题是什么? Is there any other good way to align vertically?
还有其他垂直对齐的好方法吗?
EDIT: little more HTML code: 编辑:更多HTML代码:
<div style="position:absolute;top:40%;left:0%;">
<div id="posts" style="position:relative;">
<div style="display:table-cell;vertical-align: middle;width:100%;height:100px;position:relative;text-indent: 1.5em"></div>
<div style="display:table-cell;vertical-align: middle;width:100%;height:100px;position:relative;text-indent: 1.5em"></div>
</div>
</div>
An element displayed as table-cell
without any parent explicitly displayed as table
will create its own shadowy parent displayed as such (and another in-between set as table-row
). 显示为
table-cell
的元素而没有任何父级显式显示为table
的元素将创建自己的阴影父级,显示为原来(以及另一个设置为table-row
的中间)。 It's nowhere to be seen in the DOM but it still have an effect. 它在DOM中无处可见,但仍然有效。
The default table layout algorithm is table-layout: auto
and you want table-layout: fixed
: former layout algorithm will adapt dimensions of cells to your content; 默认的表格布局算法为
table-layout: auto
而您要table-layout: fixed
:以前的布局算法将使单元格的尺寸适应您的内容; latter will respect what the author (you) says for widths. 后者会尊重作者(您)所说的宽度。 You can test by having very little content in 1 "cell" and then a very long multi-line content.
您可以通过在1个“单元格”中包含很少的内容,然后再包含非常长的多行内容来进行测试。
#posts {
position: relative;
display: table;
table-layout: fixed;
width: 100%;
}
You also should remove or adapt widths on cells: total should be 100% or else it'll be proportional on most browsers (Safari being at risk. Maybe not Saf 8 but 6 at least...) 您还应该删除或调整单元格的宽度:总和应为100%,否则在大多数浏览器中它将成比例(Safari处于危险之中。也许不是Saf 8而是至少是6 Saf ...)
I have updated your code to get it to work: 我已经更新了您的代码以使其正常工作:
<div style="position:absolute;top:40%;left:0%;width:100%;">
<div id="posts "style="position:relative;width:100%;">
<div style="display:table; width:100%;">
<div style="display:table-cell;vertical-align: middle;width:100%;height:100px;position:relative;text-indent: 1.5em;text-align:center;">test
</div>
</div>
</div>
What you needed was to add a div
with display: table
in and set all the containing elements to 100% width
. 您需要添加一个带有
display: table
的div
并将所有包含的元素设置为100% width
。 Also the div
you are centring needed a text-align: center
. 同样,您居中的
div
也需要text-align: center
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.