我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。

<body>
    <div>Div to be aligned vertically</div>
</body>

如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?


当前回答

仅垂直居中

如果您不关心InternetExplorer6和7,可以使用包含两个容器的技术。

外部容器:

应具有显示:table;

内部容器:

应具有显示:表格单元格;应垂直对齐:中间;

内容框:

应该有显示:inline块;

您可以将任何内容添加到内容框中,而不必考虑其宽度或高度!

演示:

正文{边距:0;}.外部容器{位置:绝对;显示:表格;宽度:100%;/*这可以是任意宽度*/高度:100%;/*这可能是任何高度*/背景:#ccc;}.内部容器{显示:表格单元格;垂直对齐:中间;}.居中内容{显示:内联块;背景:#fff;填充:20px;边框:1px实心#000;}<div class=“outer container”><div class=“内部容器”><div class=“居中内容”>马尔科姆在中间</div></div></div>

另请参见此Fiddle!


水平和垂直居中

如果要水平和垂直居中,还需要以下内容。

内部容器:

文本应对齐:居中;

内容框:

应重新调整水平文本对齐方式,例如文本对齐方式:左对齐;或文本对齐:右;,除非您希望文本居中

演示:

正文{边距:0;}.外部容器{位置:绝对;显示:表格;宽度:100%;/*这可以是任意宽度*/高度:100%;/*这可能是任何高度*/背景:#ccc;}.内部容器{显示:表格单元格;垂直对齐:中间;文本对齐:居中;}.居中内容{显示:内联块;文本对齐:左侧;背景:#fff;填充:20px;边框:1px实心#000;}<div class=“outer container”><div class=“内部容器”><div class=“居中内容”>马尔科姆在中间</div></div></div>

另请参见此Fiddle!

其他回答

这个解决方案适用于块元素(例如,<div>)。我用颜色使溶液更清晰。

HTML格式:

<main class="skin_orange">
    <p>As you can the the element/box is vertically centered</p>
    <div class="bigBox skin_blue">Blue Box</div>
</main>

CSS:

main {
    position: relative;
    width: 400px;
    height: 400px;
}

.skin_orange {
    outline: thin dotted red;
    background: orange;
}

.bigBox {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.skin_blue {
    background-color: blue;
}

JSFiddle代码演示

垂直和水平居中

HTML

<div id="dialog">Centered Dialog</div>

CSS

#dialog {
    position:fixed; top:50%; left:50%; z-index:99991;
    width:300px; height:60px;
    margin-top:-150px;  /* half of the width */
    margin-left:-30px; /* half of the height */}

享受

因为每次我需要垂直居中div时,我都会一遍又一遍地搜索它,这个答案总是首先出现的,所以我会把这个留给未来的我(因为提供的解决方案都不能很好地满足我的需求):

因此,如果已经在使用引导程序,可以按如下方式进行:

<div style="min-height: 100vh;" class="align-items-center row">
    <div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well

    //content goes here

    </div>
</div>

可以通过两种方式实现

body{
left: 50%; 
top:50%; 
transform: translate(-50%, -50%); 
height: 100%; 
width: 100%; 
}

OR

使用flex

body {
    height:100%
    width:100%
    display: flex;
    justify-content: center;
    align-items: center;
}

对齐项目:居中;使内容垂直居中

对齐内容:中心;使内容水平居中

当我不得不回到这个问题上时,这总是我要去的地方。

对于那些不想跳的人:

将父容器指定为位置:相对或位置:绝对。指定子容器上的固定高度。在子容器上设置位置:绝对和顶部:50%,以将顶部向下移动到父容器的中间。设置页边距上限:-yy,其中yy是子容器高度的一半,以向上偏移项目。

代码中的示例:

<style type="text/css">
    #myoutercontainer {position:relative}
    #myinnercontainer {position:absolute; top:50%; height:10em; margin-top:-5em}
</style>
...
<div id="myoutercontainer">
    <div id="myinnercontainer">
        <p>Hey look! I'm vertically centered!</p>
        <p>How sweet is this?!</p>
    </div>
</div>