A simple CSS fix
Introducing a slight modification to the original solution (tested in Chrome, Safari, and Edge):
Enhanced Solution
The initial answer encountered an issue where the image would get cut off on the left side if it was larger than the container being centered using auto margins. This resulted in an uneven distribution of space, as demonstrated in this example.
To address this, we can adjust by floating the inner
element to the right and centering based on that direction. While this does cause the image to be partially hidden on the left, it effectively prevents unnecessary horizontal scrolling on the right. Thus, the scroll is restricted only to showcase the complete image.
See the updated demonstration in this fiddle. (Note: The borders in the fiddle are purely for illustrative purposes.)
Necessary CSS Code
div.outer {
width: 300px; /* adjust as needed */
margin: 0 auto;
overflow: visible;
}
div.inner {
position: relative;
float: right; /* added line, display property removed */
right: 50%;
}
div.inner img {
position: relative;
right:-50%; /* changed from "left" in original code */
}
If you want to eliminate any right scrolling for wider images
In addition to the above adjustments, add overflow: hidden
to the parent element wrapping around outer
(such as the body
or another encompassing wrapper).
Initial Concept (For Reference)
View the original implementation in action via this fiddle. (Note: Borders in the fiddle serve as visual aids.)
HTML Markup
<div class="outer">
<div class="inner">
<img src="/yourimage.png">
</div>
</div>
CSS Styles
div.outer {
width: 300px; /* adjust as necessary */
margin: 0 auto;
overflow: visible;
}
div.inner {
display: inline-block;
position: relative;
right: -50%;
}
div.inner img {
position: relative;
left: -50%;
}