How to vertically center a div for all browsers?
I want to center a div
vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.
<body>
<div>Div to be aligned vertically</div>
</body>
How can I center a div
vertically in all major browsers, including Internet Explorer 6?
Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and working for recent versions of Firefox, Opera, Chrome, and Safari.
.outer {
display: table;
position: absolute;
height: 100%;
width: 100%;
}
.middle {
display: table-cell;
vertical-align: middle;
}
.inner {
margin-left: auto;
margin-right: auto;
width: 400px;
/*whatever width you want*/
}
<div class="outer">
<div class="middle">
<div class="inner">
<h1>The Content</h1>
<p>Once upon a midnight dreary...</p>
</div>
</div>
</div>
One more I can't see on the list:
.Center-Container {
position: relative;
height: 100%;
}
.Absolute-Center {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
border: solid black;
}
height
must be declared (see Variable Height) overflow: auto
to prevent content spillover (see Overflow) Source: Absolute Horizontal And Vertical Centering In CSS
The simplest way would be the following 3 lines of CSS:
position: relative;
top: 50%;
transform: translateY(-50%);
Following is an example:
div.outer-div {
height: 170px;
width: 300px;
background-color: lightgray;
}
div.middle-div {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
<div class='outer-div'>
<div class='middle-div'>
Test text
</div>
</div>
链接地址: http://www.djcxy.com/p/1094.html
上一篇: 垂直对齐图像旁边的文字?
下一篇: 如何垂直居中所有浏览器的div?