In CSS, setting width: 100% and leaving height set to auto (or vice versa) is often used to constrain an image. However, this can result in the image being disproportionately wide or tall.
To maintain the aspect ratio while constraining the image, consider the following approaches:
Constrain and Crop Using a DIV:
Nest the image within a DIV and set its max-width, max-height, and overflow: hidden. This will prevent the image from exceeding the specified dimensions and crop any excess.
Preserve Aspect Ratio and Limit Maximum Dimensions:
Use the max-width and max-height properties without specifying minimum dimensions. This allows the image to retain its aspect ratio while ensuring it doesn't grow larger than the maximum dimensions specified.
Example Code:
<code class="css">.image-container { max-width: 500px; max-height: 500px; overflow: hidden; } .image { width: 100%; height: auto; }</code>
This code ensures that the image within the .image-container will not exceed 500px in either width or height while maintaining its original aspect ratio.
The above is the detailed content of How to Achieve 100% Width or Height While Maintaining Aspect Ratio in CSS?. For more information, please follow other related articles on the PHP Chinese website!