How to Center Images in CSS

How to Center Images in CSS

ยท

2 min read

Believe it or not, as simple as this is, I've been centering my images by just using a flex-container or grid-container and setting the desired width to 100% and the height to auto, I never knew there was such a thing as positioning your image to fit your desired width and height until I came across some neat CSS code.

In this article, we'll be discussing how to center multiple images with custom dimensions using object-fit & object-property.

Prerequisites

  • Basic understanding of HTML & CSS

Centering Images

For you to center your images, no matter the dimensions they have, you need to use these two CSS properties:

  • object-fit : Although values can be set to
[cover | contain | fill | none | scale-down]

We'll be using the cover value soon to make sure our focus on the image center is brought out

  • object-position: Values can be set to

position
where position = [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | length-percentage ] [ top | center | bottom | length-percentage ]? | [ [ left | right ] length-percentage ] && [ [ top | bottom ] length-percentage ] ] where length-percentage = length | percentage

Check this Mozilla Documentation for more info

Okay, that looks confusing so I think it's best we look at an example illustrating this.

object-fit & object-position Example

%[codepen.io/sunkanmii-the-styleful/pen/xxpev..

On your image element style, set object-fit to cover and set object-position to be center or 50% 50% (default value) to center your image! i.e

object-fit: cover;
object-position: 50% 50%; /* default value to be at the center */

Without these, your image would look stretched and bad.

Note: For this to work, you need to set the width and height of your image element, and also note that you CANNOT use the object-position property without object-fit being set

Browser Support

And guess what? This is supported by all major browsers (Chrome, Firefox, Edge, Safari, and Opera) except for IE!

Feel free to play around with other values to set the image position and look to your liking!

Now, go make those beautiful pictures look awesome with these two CSS properties! Thanks for reading guys, I hope you have a wonderful day ahead! ๐Ÿ˜„

References

ย