Home >Web Front-end >CSS Tutorial >How to Center an Image Within a Parent Div?
Maintaining a centrally aligned image within a parent div can enhance website aesthetics and user experience. This article addresses how to achieve this alignment efficiently.
Align an image within a parent div so that its center remains at the div's center, ensuring the image spans the full height of the div without stretching its width.
Instead of applying the text-align: center; CSS declaration to the image element, add it to the parent .box element.
.box {
height: 100%; width: 450px; border: 2px solid red; background: green; overflow: hidden; text-align: center; // align center all inline elements
}
This approach ensures that all inline elements within the .box div are centered, including the image.
If a 5px gap appears beneath the image, it may result from the default line height associated with inline elements. To eliminate this gap, apply vertical-align: bottom; to the image element:
.box img {
height: 100%; width: auto; vertical-align: bottom; // fix the vertical gap
}
By implementing these modifications, you can effectively center your image within the parent div and ensure its desired appearance.
The above is the detailed content of How to Center an Image Within a Parent Div?. For more information, please follow other related articles on the PHP Chinese website!