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
whereposition
= [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right |length-percentage
] [ top | center | bottom |length-percentage
]? | [ [ left | right ]length-percentage
] && [ [ top | bottom ]length-percentage
] ] wherelength-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
andheight
of your image element, and also note that you CANNOT use theobject-position
property withoutobject-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! ๐