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!