Home  >  Article  >  Web Front-end  >  How to Center an Image within a Parent Div While Preserving Height and Aspect Ratio?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 02:30:29858browse

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

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>

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>

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!

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