Home >Web Front-end >CSS Tutorial >How to Center an Image Within a Parent Div?

How to Center an Image Within a Parent Div?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 01:54:02253browse

How to Center an Image Within a Parent Div?

Centering 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.

Problem Statement:

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.

Solution:

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.

Additional Considerations:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn