如何在浮动父元素(已知大小)内垂直居中任意大小的子元素?
如何将任意大小的子元素垂直居中在浮动父元素(已知大小)内?
显示:表格单元格;当元素浮动时,vertical-align: middle;
似乎不再起作用。
我在这里创建了一个SSCCE:http://mathiasbynens.be/demo/center -vertically-inside-float
不带浮动,一切都按预期进行。但是一旦父元素浮动,垂直方向对齐失败。
有什么想法可以解决这个问题吗?
编辑:我应该补充一点,子元素应该是图像。在我的示例页面中,我使用了段落,因为我假设我可以使用 display: block;
p 元素所需的任何 CSS 应用到 img
元素> 也是如此。 (失败。)
How to vertically center a child element of arbitrary size inside a floated parent element (of known size)?
display: table-cell; vertical-align: middle;
no longer seems to work when the element is floated.
I created an SSCCE here: http://mathiasbynens.be/demo/center-vertically-inside-float
Without float, everything works as it should. But as soon as the parent element is floated, the vertical alignment fails.
Any ideas how to work around this?
Edit: I should’ve added that the child elements are supposed to be images. In my example page I’m using paragraphs, since I assumed I could apply whatever CSS those p
elements needed to img
elements with display: block;
as well. (Fail.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果是单行,则将
p
的line-height
设置为容器的高度。If it's one-liner, then set
line-height
ofp
to height of the container.浮动会禁用表格单元格,因为单元格不能浮动。所以基本上我会推荐标准的东西——使用浮动垫片技术或绝对定位。
Float disables table-cell, because cells can’t be floated. So basically I would recommend the standard stuff – using floated shim technique or absolute positioning.
好的,感谢 porneL的回答,我找到了解决我问题的方法。
在我的 SSCCE 中,我使用段落作为子元素(到目前为止,porneL 给出了正确的答案),但我真正需要的是图像。事实证明这需要一些额外的 CSS:
谢谢你们的帮助,伙计们!
Ok, so thanks to porneL’s answer, I found the solution to my problem.
In my SSCCE I used paragraphs as child elements (and porneL gave the correct answer as far as that goes), but what I really needed were images. Turns out this needs a little bit of additional CSS:
Thanks for the help, guys!