I have a div which contains two child divs, and they are intended to be part of fluid layout, so I can't set a fixed size for them in px.
There are two goals here:
Align the two child divs horizontally, which I have achieved using float: left
and float: right
respectively.
Vertically center the text (within the child divs) relative to the parent div. The text is short and takes a single line by design.
What I have now: http://jsfiddle.net/yX3p9/
Apparently, the two child divs do not take the full height of the parent div, and therefore their text are not vertically centered relative to the parent div.
Conceptually, to achieve the goals above, we can either make the child divs vertically centered within the parent div, or we can make the child divs take the full height of the parent div. What is the robust way to do so?
*Browser support: IE 9+ and other usual modern browsers.
We set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set its value to middle. Anything inside this child div will be vertically centered.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
The two child elements . left and . right are positioned absolutely with top: 50% and use margin-top: -0.8em to get vertical centering (use one-half of line-height value). Use the left and right offsets (or padding) to adjust the child elements horizontal position as needed.
I prefer the usage of transform above the above answers.
top: 50%; transform: translateY(-50%); -ms-transform: translateY(-50%); -moz-transform: translateY(-50%); -webkit-transform: translateY(-50%); -o-transform: translateY(-50%);
In my experience it works in many situations and on all major browsers (even IE9+).
If you use SCSS, you might even like to implement this mixin:
@mixin v-align($position: absolute){ position: $position; top: 50%; transform: translateY(-50%); -ms-transform:translateY(-50%); /* IE */ -moz-transform:translateY(-50%); /* Firefox */ -webkit-transform:translateY(-50%); /* Safari and Chrome */ -o-transform:translateY(-50%); }
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