Simple Trick: Centering Elements in SCSS
There are many situations when a developer needs to center an element on a page. Sometimes, when you give it an absolute position using a manual top/bottom and left/right, it causes problems with responsive design. Other times text-align: center just doesn’t work. In some cases the content will end up changing or the page needs to be responsive in more than just a horizontal plane. When these types of situations happen, it’s helpful to use a different method for centering content.
Sometimes you need text, images, or pseudo elements to float in the middle of a container and stay put regardless of content size. You might think to just set the element to position: absolute and give it a top and bottom of 50%. In actuality, this position isn’t based off the center of the element itself, so it ends up slightly off center.
One centering trick is to add transform: translate() to the styles. It’s responsive and works on any element as long as it has a parent container. This trick lets you adjust for the element’s misalignment by moving it over by half its width or height, depending exactly on how you use the translate. You’ll end up with a perfectly centered element even when browser sizes change.
Here’s how to do it:
1. Wrap the content you want to center in a div container
2. Set the wrapper container to position: relative
3. Set the content to position: absolute
4. For vertical and horizontal positions, use these styles:
For vertical only:
For horizontal only:
For both vertical and horizontal:
transform: translate(-50%, -50%)
When text-align: center or vertical-align: top doesn’t work, this trick lets you center literally anything within a parent element. Use it for floating text, images, pseudo elements, just plain divs or spans, navigation text, header logos, tooltip bubble pointers, promotional banner text, and just about anything else you can think of. The best part is that it’s responsive, too.
For more on responsive design and development check out our post, A Developer’s Dilemma: Responsive Design and the Vertical Scrollbar.
Mike McRoy is an applications engineer on the eCommerce Implementation team at LYONSCG. He is a certified Demandware developer who has been working with the platform since 2014. Mike began his web development career in 2003 when he launched a local freight truck hardware distributor’s website.