在一个百分比高度的div中垂直居中一个div

11

在一个百分比高度的 div 中垂直居中一个 div,是否可能?


相关(但不是完全重复):垂直对齐Divs - Andy E
请检查以下链接:http://jsfiddle.net/ERuX4/1/ https://dev59.com/UGLVa4cB1Zd3GeqPvFGp#10010055 - ShibinRagh
这是一个在IE,Firefox和Chrome上工作的示例。http://jsfiddle.net/ETKhu/ 很可能对你将来的工作有用 :) - Ricardo Rodrigues
工作示例。更简单的方法是:jsfiddle.net/NT8Mn - pratik
5个回答

15

这个问题已经在这里以及整个互联网上被问了很多次。

快速搜索会带给你大量的结果。不过,我个人偏好的方法是使用display: table-cell;vertical-align: middle;。参见这个页面的示例。(请注意,这在Internet Explorer 6上无法工作。)


2
是的,我确实在互联网上搜索了, 但是结果太多了,我不知道哪些是有效的,哪些已经过时了。谢谢。 - Hailwood
另外,还有一种不需要复杂的CSS来实现这个的方法。试试这个链接:jsfiddle.net/NT8Mn - pratik
我在互联网上搜索,这是最顶部的结果。 - blockloop

6
如果你的内部
具有绝对高度(比如说100像素),你可以这样做:
.outerdiv{
  position: relative; // Or absolute, or fixed
  height: 80%;
}

.innerdiv{
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;  // It's at 50%, but not really centered
  margin-top: -50px; // So just move it up by the half of its height :D
}

我并不太喜欢这个解决方案,我相信还有很多其他可能性(比如使用表格或 display: table-cell;)- 但这是我首先想到的...


3
.outerdiv {
  display: table-cell;
  vertical-align: middle;
}

警告 - 这并不适用于所有浏览器!


0

不需要使用px单位。

topbottomrightleft改为百分比:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
    </head>

    <body>
        <div style="position: absolute;
                    top: 0;
                    bottom: 0;
                    right: 0;
                    left: 0;
                    text-align: center;
                    white-space: nowrap;
                    overflow: hidden;">
            <div style="position: relative;
                        display: inline-block;
                        height: 100%;
                        vertical-align: middle;"></div>
            <div style="background-color: #FEEF88;
                        position: relative;
                        display: inline-block;
                        vertical-align: middle;">Hola todo el mundo :D</div>
        </div>
    </body>
</html>

0

我喜欢使用以下技术,其中包含两个容器:

外部容器:

  • 应该有 display: table;

内部容器:

  • 应该有 display: table-cell;
  • 应该有 vertical-align: middle;

内容框:

  • 应该有 display: inline-block;

您可以将任何内容添加到内容框中,而不用担心其宽度或高度!

此外,您可以通过在内部容器中添加 text-align:center; 轻松添加水平居中。

演示:

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Malcolm in the Middle
     </div>
   </div>
</div>

这个小抄

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接