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?
you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%.
Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.
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 worked for recent versions of Firefox, Opera, Chrome, and Safari.
.outer { display: table; position: absolute; top: 0; left: 0; 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>
View A Working Example With Dynamic Content
I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.
The simplest way would be the following three lines of CSS:
1) position: relative;
2) top: 50%;
3) 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With