The Easy Way to Absolute Center (vertical + horizontal alignment)
by
, 05-27-2016 at 12:29 PM (18777 Views)
I hit a snag recently when I wanted to absolutely center a responsive image and couldn't use my 'go-to' method of CSS3 transforms, due to other conflicting CSS3 keyframe animations that were cancelling it out;Here's the CSS3 transform centering technique in action (IE9+): http://output.jsbin.com/caziwuzuziCode:img { max-width: 100%; max-height: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); transform: translate(-50%,-50%) }
I tried many other techniques, such as CSS tables/align-middle and flexbox (most listed here: https://css-tricks.com/centering-css-complete-guide/), but it turned out that the easiest way was a little-documented trick usingposition:absolute;
andmargin:auto;
When most front-end developers think about centering an element using absolute positioning, they think of the 'top/left 50% with top/left negative margins' technique, which works very well if you know the size of the centered element;But this doesn't work when you don't know the size of the element - such as with a responsive image.Code:img { width: 500px; height: 300px; position: absolute; top: 50%; left: 50%; margin-top: -150px; /* half the element's height */ margin-left: -250px; /* half the element's width */ }
The solution is to absolutely pin the element to each side of its container, and then letmargin:auto;
move it to vertical and horizontal center;Here's how that looks: http://output.jsbin.com/tupiyoyufeCode:img { max-width: 100%; /* responsive image */ max-height: 100%; /* responsive image */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto /* center horizontally and vertically */ }
Simple, right?
And it even works back to IE8
If you're curious about what I was working on, it was this - Responsive Modal Overlay/ Pop-up Image Viewer with Entrance Effects: http://fofwebdesign.co.uk/template/_...up-effects.htm
View the source code for the HTML, CSS and JavaScript. It's also worth noting that you can mix up the animation effects in the JS function calls;Experiment with what's there or why not try your own keyframe animations!Code:modalImg('.popup.zoom', 'zoomin', 'dropout');
Have a great weekend!