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

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

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


当前回答

我认为,对于所有不使用Flexbox的浏览器来说,“alignitems:center;”是一种显示:表格和垂直对齐:中间;的组合;。

CSS

.vertically-center
{
    display: table;

    width: 100%;  /* Optional */
    height: 100%; /* Optional */
}

.vertically-center > div
{
    display: table-cell;
    vertical-align: middle;
}

HTML

<div class="vertically-center">
    <div>
        <div style="border: 1px solid black;">some text</div>
    </div>
</div>

演示:https://jsfiddle.net/6m640rpp/

其他回答

垂直和水平居中

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

享受

通过使用transform属性,我们可以轻松地进行垂直居中的div。

.main分区{背景:无重复滚动0 0#999;字体大小:18px;高度:450px;最大宽度:850px;填充:15px;}.垂直中心{背景:无重复滚动0 0#1FA67A;颜色:#FFFFFF;填充:15px;位置:相对;顶部:50%;变换:translateY(-50%);-moz变换:translateY(-50%);-webkit转换:translateY(-50%);-ms变换:translateY(-50%);-o变换:translateY(-50%);}<div class=“main div”><div class=“垂直中心”><span>“Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incident ut labour et dolore magna aliqua。ut enim ad minim veniam,quis nostrud exerciation ullamco labours nisi ut aliquip ex a commo consequat。Duis aute irure dolor in representate velit esse cillum dolore eu fugiat nula pariator。例外情况下,在非政府组织的支持下,必须承担责任。”我正式任命了一位不称职的莫利特。“”</span></div></div>

请参阅此处了解全文

这里有一个简单的方法,几乎没有代码:

CSS代码:

.main{
    height: 100%;
}

.center{
    top: 50%;
    margin-top: 50%;
}

HTML代码:

<div class="main">
    <div class="center">
        Hi, I am centered!
    </div>
</div>

您的文本将位于页面中间!

实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。

#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>

这是结果。

特别是对于具有相对(未知)高度的父div,未知解决方案中的居中对我来说非常有用。

它在Chrome、Firefox、Opera和Internet Explorer中进行了测试。

/*此父项可以是任何宽度和高度*/.块{文本对齐:居中;}/*鬼魂被推着保持完美的居中*/.block:之前{内容:“”;显示:内联块;高度:100%;垂直对齐:中间;右边距:-0.25em;/*调整间距*/}/*要居中的元素可以也可以是任何宽度和高度*/.居中{显示:内联块;垂直对齐:中间;宽度:300px;}<div style=“width:400px;height:200px;”><div class=“block”style=“高度:90%;宽度:100%”><div class=“center”><h1>一些文本</h1><p>任何其他文本。。。“”</p></div></div></div>