![]() |
VOOZH | about |
To center an image in CSS, we will align the image to the container horizontally and vertically as the layout requires.
The simplest way to center an image horizontally within a block-level container is to use the text-align property. This method works well when the image is inline or inline-block.
.parent {
text-align: center;
}
Output
When the image is set as a block element, you can center it by setting the left and right margins to auto.
img {
display: block;
margin-left: auto;
margin-right: auto;
}
Output
Flexbox is a layout model that allows for easy centering of images both horizontally and vertically. By setting the display of the container to flex, you can center the image with minimal code.
.parent {
display: flex;
justify-content: center;
}
Output
CSS Grid also allows for straightforward centering. By defining a grid container and using the place-items property, you can center images with ease.
.parent {
display: grid;
place-items: center;
}
Output
If you want to center an image vertically within a fixed-height container, you can set the line-height of the container equal to its height. This method works well for single-line text and small images.
Output
Absolute positioning can allows the precise placement of the element relative to its nearest positioned ancestor. By combing the absolute positioning with transforms, we can center the element with its container.
.parent {
position: relative;
height: 100vh;
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Output
When centering images within a larger container, it's essential to ensure that the container has defined dimensions. Hereโs how to center an image within a fixed-size container using Flexbox.
Output