I am trying to vertically center two elements.
I followed the tutorial at phrogz.net but still the elements get placed above the div, below th
Here are two ways to center divs within divs.
One way uses CSS Flexbox and the other way uses CSS table and positioning properties.
In both cases, the height of the centered divs can be variable, undefined, unknown, whatever. The height of the centered divs doesn't matter.
Here's the HTML for both:
<div id="container">
<div class="box" id="bluebox">
<p>DIV #1</p>
</div>
<div class="box" id="redbox">
<p>DIV #2</p>
</div>
</div>
#container {
display: flex; /* establish flex container */
flex-direction: column; /* stack flex items vertically */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 300px;
border: 1px solid black;
}
.box {
width: 300px;
margin: 5px;
text-align: center;
}
DEMO
The two child elements (.box
) are aligned vertically with flex-direction: column
. For horizontal alignment, switch the flex-direction
to row
(or simply remove the rule as flex-direction: row
is the default setting). The items will remain centered vertically and horizontally (DEMO).
body {
display: table;
position: absolute;
height: 100%;
width: 100%;
}
#container {
display: table-cell;
vertical-align: middle;
}
.box {
width: 300px;
padding: 5px;
margin: 7px auto;
text-align: center;
}
DEMO
Which method to use...
If you're not sure which method to use, I would recommend flexbox for these reasons:
Browser support
Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.
Add the following: display:table; to bannerRight
display:table-cell; and vertical-align:middle; to bannerrightinner
I have not tried this, please give me feedback if it does not work. ;)
EDIT: forgot to mention: take 'float' and 'position' properties off