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

Barbara Streisand
Release: 2024-10-23 22:15:30
Original
514 people have browsed it

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 */
}
Copy after login

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 */
}
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!