How do I allow a dynamic (changing in height) content area to be vertically centered on the users screen (regardless of screen size), UNTIL it reaches the point where there is only 100px
left of free space at the top of the page?
Here's a diagram:
I'm not entirely sure whether the solution to this problem will use only CSS or javascript - so all suggestions are welcome.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
centering vertically - putting your view in the center of the parent according to its height. centering horizontally - putting your view the center of your parent according to its width.
CSS Demo: vertical-alignThe vertical-align property can be used in two contexts: To vertically align an inline element's box inside its containing line box. For example, it could be used to vertically position an image in a line of text. To vertically align the content of a cell in a table.
Use the CSS line-height property Add the line-height property to the element containing a text larger than its font size. By default, equal spaces will be added above and below the text, and you'll get a vertically centered text.
My solution takes into account that you want your content to be centered on the whole page and not just "in the space below". I used negative margins to achieve this.
See the working example here:
http://jsfiddle.net/WkQzw/5/
HTML:
<div id="container">
<div id="table">
<div id="cell">
<div id="content">Some content</div>
</div>
</div>
</div>
CSS:
#container {
width: 100%;
height: 100%;
padding: 100px 0;
margin-top: -100px;
}
#table {
display: table;
width: 100%;
height: 100%;
margin-top: 100px;
}
#cell {
display: table-cell;
vertical-align: middle;
}
#content {
background-color: lightblue;
width: 50%;
margin: 0 auto;
}
Tested:
Update:
I used box-sizing: border-box;
but Firefox required an additional -moz-box-sizing: border-box;
. Now it works also in Firefox.
This is based off of ToniTornado's answer, but with far less wrappers needed.
See fiddle demo
HTML
<div id="container">
<div id="content">Some content</div>
</div>
CSS (minimum for vertical positioning)
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
body {
display: table;
padding-top: 100px;
margin-top: -100px;
}
#container {
display: table-cell;
vertical-align: middle;
padding-top: 100px;
}
As the above fiddle showed, the above css centers the #content
on the screen space. If you prefer to center on the space left below the top area, then adjust the body
by removing the negative top margin and the #container
by removing its top padding, like this fiddle and this css shows:
body {
display: table;
padding-top: 100px;
}
#container {
display: table-cell;
vertical-align: middle;
}
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