Home > Article > Web Front-end > How Can I Center an Oversized Image Within a Div Using CSS?
When working with a fluid layout where the div width varies, centering an oversized image within a div can be challenging. The image may start at the left edge, leaving it off-center to the right.
To address this issue, we propose a CSS solution that effectively centers the image, creating an even overflow cutoff on both edges:
<code class="css">.parent { position: relative; overflow: hidden; } .child { position: absolute; top: -9999px; bottom: -9999px; left: -9999px; right: -9999px; margin: auto; }</code>
The parent div establishes a relative positioning and contains the overflow. The child div, which contains the image, has absolute positioning with extremely negative top, bottom, left, and right values. These negative values effectively push the image beyond the visible area of the div. The margin: auto property ensures automatic centering of the image within the parent div.
This technique allows the image to maintain its original aspect ratio, eliminating any browser-imposed resizing issues that may compromise image quality. The result is a centered oversized image with overflow that is evenly cropped on both sides.
The above is the detailed content of How Can I Center an Oversized Image Within a Div Using CSS?. For more information, please follow other related articles on the PHP Chinese website!