Search
Learn
Share

Pure CSS: DRY Centered element with an absolute position [UPDATE]

Published by Profile Image LGK on 9 December, 2016
75 views
Maybe you already know this trick to bring an absolute positioned element into the middle:

#box {
position: absolute;
width: 400px;
height: 225px;

left: 50%;
margin-left: -200px; /* half of the width */

top: 50%;
margin-top: -112.5px; /* half of the height */
}

But this method is not really DRY (don't repeat yourself). If you want to change the width property, you also have to update the margin-left property and to recalculate it.

So instead you could take advantage of CSS variables. Like this:

:root {
/* Set the width and height only once */
--box-width: 400px;
--box-height: 225px;
}

#box {
position: absolute;
width: var(--box-width);
height: var(--box-height);

/* Take 50% and substract the half of the box from it */
left: calc(50% - var(--box-width)/2);
top: calc(50% - var(--box-height)/2);
}

Warning: While I'm writing this Microsoft Edge does not yet support CSS variables. But they are working on it. You can see the current state here: https://developer.microsoft.com/en-us/microsoft-edge/platform/status/csscustompropertiesakacssvariables/?q=CSS%20Custom%20Properties%20category%3Acss

See the live demo on CodePen: http://codepen.io/lgkonline/pen/YNzqXz

I've updated this solution. You can see the original one here: http://codepen.io/lgkonline/pen/aBKeZM