How to Center an Image within a Parent Div While Preserving Height and Aspect Ratio?

Barbara Streisand
Release: 2024-10-24 02:30:29
Original
905 people have browsed it

How to Center an Image within a Parent Div While Preserving Height and Aspect Ratio?

Center Image Element within Parent Div

Centering an image within its parent div requires specific CSS techniques. Here's how to achieve this:

Problem:

How to align an image in the middle of its parent div while preserving its height (100%) without stretching its width?

Example:

Consider the HTML and CSS provided in the question:

<code class="html"><div class="box">
  <img src='featured.jpg' />
</div></code>
Copy after login
<code class="css">.box {
  height: 100%;
  width: 450px;
  border: 2px solid red;
  background: green;
  overflow: hidden;
}
.box img {
  height: 100%;
  width: auto;
  text-align: center;
}</code>
Copy after login

Solution:

To center the image, add the text-align: center; CSS declaration to the parent div instead of the child image element:

<code class="css">.box {
  /* ... */
  text-align: center;  /* Align center all inline elements */
}</code>
Copy after login

This centers all inline elements within the div, including the image.

Additional Enhancement:

There may be a gap below the image due to the reserved line height for inline elements. To remove this gap, add vertical-align: bottom; to the image CSS:

<code class="css">.box img {
  /* ... */
  vertical-align: bottom;  /* Fix the vertical gap */
}</code>
Copy after login

The above is the detailed content of How to Center an Image within a Parent Div While Preserving Height and Aspect Ratio?. 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!