Assuming the parent element has position: relative;
, these four properties will center a child element both horizontally and vertically inside, no matter what the width of height of either are.
@mixin centerer {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
position: relative;
}
.child {
@include centerer;
}
See the Pen Centerer Mixin by Chris Coyier (@chriscoyier) on CodePen.
Although beware if the child element being centered is taller than parent, the top could get cut off.
Fancier
If you want to be able to center in only one direction…
@mixin centerer($horizontal: true, $vertical: true) {
position: absolute;
@if ($horizontal and $vertical) {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} @else if ($horizontal) {
left: 50%;
transform: translate(-50%, 0);
} @else if ($vertical) {
top: 50%;
transform: translate(0, -50%);
}
}
See the Pen yybgZd by Chris Coyier (@chriscoyier) on CodePen.
What are your thought’s on using display: table; on the parent and display: table-cell; on the child with vertical-align etc. to achieve a similar outcome?
I use that technique a lot but it makes me feel a little dirty. It would be good to see another opinion.
Is there any specific reason to use a mixin for this and not a placeholder selector, or does it just come down to taste?
Thanks for this Chris. Quick heads up that the Fancier version is missing a % for the $vertical bit and thus is not centering correctly in the example.
Thanks for the mixin. I modified a bit to center right and bottom. I’m new to sass so I’m wondering if there might be a cleaner way to do this:
http://codepen.io/ilokano/pen/mJxJPL
Nice mixin!
However, there’s a typo in the else if section:
You forgot the %. Should be translate(0, -50%);
Cheers!
CSS transform needs to be prefixed for full browser support.
http://shouldiprefix.com/#transforms
-webkit-transform: mytransform(); /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 /
-ms-transform: mytransform(); / IE 9 /
transform: mytransform(); / IE 10, Fx 16+, Op 12.1+ */
Please use AutoPrefixer instead of writing browser prefixes.
This technique works OK, but when user zooms the page, it is not exactly 100% accurate. Please try zooming this pen: http://codepen.io/anon/pen/NxBXOP
Why not use this? I find it to be much more suitable.
Your parent needs to have a set height for this to work, right?
Thanks! Converted to LESS if anyone is interested:
http://codepen.io/leggomuhgreggo/pen/JXqgxP?editors=0100
Love your code! I was previously doing this with three separate LESS mixins. This saved me from having to pick apart sass code.
I’ve tweaked it a bit to make it even simpler / more readable. Also switched to mixins for vender prefixes.
http://codepen.io/callaginn/pen/mAZmKE