Home  >  Article  >  Web Front-end  >  How to Position an Image Vertically and Horizontally Centered within a Parent Div?

How to Position an Image Vertically and Horizontally Centered within a Parent Div?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 22:15:30515browse

How to Position an Image Vertically and Horizontally Centered within a Parent Div?

Centering Image Elements within Parent Divs

When seeking to position an image centrally within its parent div, the desired outcome is for the image to remain centered vertically within the parent, while also maintaining its inherent height.

Solution:

To achieve this effect, modify the CSS declaration of the parent .box div, rather than the child .box img div, by adding text-align: center;. This amendment ensures that all inline elements within the parent div are aligned centrally.

.box {
    height: 100%;
    width: 450px;
    border: 2px solid red;
    background: green;
    overflow: hidden;
    text-align: center;  /* align center all inline elements */
}

Consequently, the updated CSS guarantees that the image element will always be positioned in the center of its parent div, maintaining its actual height.

Addressing Vertical Gap Issue:

Upon further examination, it was discovered that a 5px gap had appeared beneath the centered image. This gap is attributable to line height reservation for inline elements like . To eliminate this gap, vertical-align: bottom; should be added to the image's CSS.

.box img {
    height: 100%;
    width: auto;
    vertical-align: bottom; /* <-- fix the vertical gap */
}

By following these steps, you can effectively center images within parent divs, maintaining their intended height while eliminating any unintended vertical gaps.

The above is the detailed content of How to Position an Image Vertically and Horizontally Centered 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