繁体   English   中英

如何在100%高的另一个元素内垂直居中放置一个元素?

[英]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>

的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;
}

如果要查看示例,其中block元素占据了视口高度的100%-那么请看一下: before ... after

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM