如何将元素垂直居中于另一个100%高度的元素?

时间:2013-11-03 13:55:55

标签: html css

我正在使用这种技术http://codepen.io/chriscoyier/pen/gsodI。它几乎是好的 - 但在第二个框中你可以看到内容框突出外部元素。

如何解决这个问题,以便如果内部元素小于外部元素,它会居中,如果它更高,它会像在此图像中那样“推动”外部元素?

enter image description here

4 个答案:

答案 0 :(得分:1)

你需要给三个主要属性来垂直对齐

  • 身高:......;
  • 显示:table-cell;
  • vertical-align:middle;

答案 1 :(得分:0)

在第二个框中,更改此行:

<div class="block" style="height: 200px;">

这个:

<div class="block" style="min-height: 200px;">

答案 2 :(得分:0)

在你的CSS中

vertical-align:middle

答案 3 :(得分:0)

This seems to be what you are describing。 (演示中的第二个例子)

要解决此问题,请将display:table;width: 100%添加到块(父)元素

<强> UPDATED FIDDLE

标记

<div class="block">    
    <div class="centered">
    </div>   
</div>

CSS

/* 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;
}

如果您想查看块元素占据视口高度100%的示例,请查看以下内容:before ... after