Blog (my web musings)

Find out what's interesting me, get tips, advice, and code gems that don't fit elsewhere.


Search Blog


I hit a snag recently when I wanted to absolutely centre 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;

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%)
    }

Here's the CSS3 transform centering technique in action (IE9+).

I tried many other techniques, such as CSS tables with vertical-align :middle; and flexbox (most listed in the CSS Tricks Centering in CSS Guide), but it turned out that the easiest way was a little-documented trick using position:absolute; and margin: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;

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 */
    }

But this doesn't work when you don't know the size of the element - such as with a responsive image.

The solution is to absolutely pin the element to each side of its container, and then let margin:auto; move it to vertical and horizontal center;

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 */
    }

Here's how that looks. 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

Demo

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;

modalImg('.popup.zoom', 'zoomin', 'dropout');

Experiment with what's there or why not try your own keyframe animations!