Align image in center and middle within div
To center-align an image inside a div, utilize the flexibility of CSS Flexbox:
Set two stellar properties display: flex
, align-items: center
for vertical and justify-content: center
for horizontal centering. Ensure the image behaves within the div using max-width
and max-height
.
Multiple methods for impressive centering
We've seen the elegance of flexbox method, so let's be explorers and dig into other efficient ways for the sake of deeper understanding and compatibility.
Absolute positioning to the rescue
Tutelage in absolute positioning with a dash of relative positioned parent:
This code instructs the image to troll physics by pulling back by 50% of its own width and height.
Inline-block for responsive and friendly centering
To court the traditionalists or those stuck with older browsers, inline-block flirts:
Here, the parent's line-height
matches much with its height, allowing vertical-align
to perform the centering waltz with the image.
Embrace the power of CSS grid
CSS Grid isn't left out. Powerful and yet so humble:
The mysterious place-items
is a catch-all shorthand that takes care of both horizontal and vertical alignment.
Taking into account practical scenarios and considerations
Different scenarios demand different heroes for centering. Your toolbox should never be depleted.
Centering in a mysterious container
When the div dimensions pull a Houdini, flexbox and grid are a dream team that adapt with ease.
Centering that isnβt just for the images
Text, inline elements, basically everything non-replaceable? Cast a text-align: center;
for horizontal and sprinkle line-height:
for verticalβif you get the height to spill the beans.
A nod to the browser compatibility
To get applause from older browsers like IE6, take to the stage with table-cell display properties:
Aspect ratio? Check.
Keep the picture perfect ratio with max-width
and max-height
rather than direct values for organic scaling within the container.
Layout shifts? Not today.
Use width and height attributes or aspect ratio boxes to keep layout shifts at bay while images load.
Was this article helpful?