![](/img/trans.png)
[英]How to center an element vertically inside a container which has a float element which sometimes affects the final height of the container?
[英]How to center an element vertically inside another element that is 100% height?
我正在使用此技术http://codepen.io/chriscoyier/pen/gsodI 。 几乎是不错的-但是在第二个框中,您可以看到内容框伸出了外部元素。
如何解决此问题,以便如果内部元素小于外部元素,则将居中,如果内部元素较高,则将其“推”到此图像中?
您需要提供三个主要属性以垂直对齐
在第二个框中,更改以下行:
<div class="block" style="height: 200px;">
为此:
<div class="block" style="min-height: 200px;">
在你的CSS
vertical-align:middle
这似乎就是您所描述的 。 (演示中的第二个示例)
要解决此问题,请添加display:table;
和width: 100%
到块(父)元素
<div class="block">
<div class="centered">
</div>
</div>
/* This parent can be any width and height */
.block {
text-align: center;
background: orange;
display: table; /* added this */
width: 100%; /* added this */
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
background: pink;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.