eyehack.home();

/* A blog about frontend web development. */

Archive for the ‘CSS’ Category

Center a large image in a smaller element of unknown size with pure CSS

February 15th, 2016

Often I need to work with images coming from a third party. Sometimes the sizes of those images aren’t known, and the aspect ratios do not meet the needs of the design.

If possible, it’s always going to be better to process and serve images that are not bigger then what is needed of course. But time doesn’t always allow that, and it comes with it’s own set of issues (how/what to crop, storage, caching etc.)

An Example

  • We have a large rectangular image of unknown dimensions
  • We need make it a smaller square
  • We need to keep the image centered within the square
  • The size of the square can change, even into a rectangle

If we knew the dimensions of the image, we could do something like this:

See the Pen Center a large image in a smaller element of known size with pure CSS by Matt R (@goshdarnheck) on CodePen.

But when the dimensions are unknown, this trick won’t work because we can’t set the correct margin value.

That’s where the CSS property transform comes into play. We can use the translateX function value to move the image back over by 50%, similar to the solution above:

See the Pen Center a large image in a smaller element of unknown size with pure CSS by Matt R (@goshdarnheck) on CodePen.

The dimensions of the containing div can change, the size and ratio of the image can change, and the image will still stay centered. This can be combined with media queries or a percent sized container for a responsive effect.