如何在div中垂直居中具有可变高度的内容?当内容的高度可变时,垂直居中div内容的最佳方法是什么。在我的特殊情况下,容器div的高度是固定的,但如果有一个解决方案可以在容器具有可变高度的情况下工作,那将是很好的。此外,我想要一个没有或很少使用CSS黑客和/或非语义标记的解决方案。
3 回答

holdtom
TA贡献1805条经验 获得超10个赞
这似乎是我发现这个问题的最佳解决方案,只要你的浏览器支持::before
伪元素:CSS-Tricks:以未知为中心。
它不需要任何额外的标记,似乎工作得非常好。我无法使用该display: table
方法,因为table
元素不遵守该max-height
属性。
.block { height: 300px; text-align: center; background: #c0c0c0; border: #a0a0a0 solid 1px; margin: 20px;}.block::before { content: ''; display: inline-block; height: 100%; vertical-align: middle; margin-right: -0.25em; /* Adjusts for spacing */ /* For visualization background: #808080; width: 5px; */}.centered { display: inline-block; vertical-align: middle; width: 300px; padding: 10px 15px; border: #a0a0a0 solid 1px; background: #f5f5f5;}
<div class="block"> <div class="centered"> <h1>Some text</h1> <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said—"Did ye see anything looking like men going towards that ship a while ago?"</p> </div></div>

肥皂起泡泡
TA贡献1829条经验 获得超6个赞
这是我需要多次执行的操作,一致的解决方案仍然需要添加一些非语义标记和一些特定于浏览器的黑客。当我们获得css 3的浏览器支持时,你将获得垂直居中而不会犯罪。
基本上它涉及添加一个额外的元素,并在IE和支持position:table\table-cell
非表元素的浏览器中应用不同的样式。
<div class="valign-outer"> <div class="valign-middle"> <div class="valign-inner"> Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me. </div> </div></div><style> /* Non-structural styling */ .valign-outer { height: 400px; border: 1px solid red; } .valign-inner { border: 1px solid blue; }</style><!--[if lte IE 7]> <style> /* For IE7 and earlier */ .valign-outer { position: relative; overflow: hidden; } .valign-middle { position: absolute; top: 50%; } .valign-inner { position: relative; top: -50% } </style> <![endif]--><!--[if gt IE 7]> --><style> /* For other browsers */ .valign-outer { position: static; display: table; overflow: hidden; } .valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }</style>
- 3 回答
- 0 关注
- 580 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消