Centering images is a very common layout task in CSS. You can center an image horizontally using display: block with auto margins, or use display: flex on a parent container to center it both horizontally and vertically.
In this note, you will see how to:
margin-left: auto and margin-right: auto share remaining space equally, centering the element.display: flex can center its children along the main and cross axes.max-width: 100% to keep images responsive.display: block + Auto MarginsTurn the image into a block-level element and set left and right margins to auto. This centers the image horizontally inside its parent.
/* Center a single image horizontally using auto margins */
img.center-block {
display: block;
margin-left: auto;
margin-right: auto;
width: 250px;
max-width: 100%;
}
<!-- Image centered inside its parent block -->
<img
src="https://images.pexels.com/photos/3987066/pexels-photo-3987066.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt="Centered Block Image"
class="center-block"
/>
Wrap the image in a container and turn that container into a flexbox. Then use justify-content: center and align-items: center to center the image horizontally and vertically.
/* Flex container that centers its child image horizontally and vertically */
.flex-container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
background: #f0f0f0;
}
<!-- Parent flex container with a centered image inside -->
<div class="flex-container">
<img
src="https://images.pexels.com/photos/3987066/pexels-photo-3987066.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt="Flex Centered Image"
/>
</div>
The image below is centered horizontally using block display and auto margins.

The image is centered both horizontally and vertically inside the flex container.

display: block with auto margins for simple horizontal centering of a single image.max-width: 100% so they shrink on smaller screens.text-align: center only centers inline or inline-block elements, not block-level elements like a block image.height or content) for vertical centering to be visible.display: block with margin-left: auto and margin-right: auto.<div> and center it using Flexbox with justify-content: center and align-items: center.align-items to flex-start and flex-end to see how vertical alignment changes inside the flex container.