You can actually do this by setting the margin-left
and margin-right
on the image to -100%
.
Here's a jsFiddle demonstrating this. (use the one below instead, it's better)
It is an even better idea to set the margin-left
and margin-right
on the image to a much larger negative number, e.g. -9999%
, as with the -100%
value, the image starts to move off-center as soon as the div
's containing element becomes less wide than 3 times the width of the div
:
margin-left: -100% + the div's width: 100% + margin-right: -100% = 3x div width
You can check the difference in behaviour between this jsFiddle and the previous one by toggling the overflow to visible and resizing the result window to less than 300%
of the width of the div
.
Quoting @MaxOriola on the range of supported browsers (from the comments):
I've retested second fiddle ... in Firefox, Chrome, Safari (last versions) and Explorer 8, 9, 10. Works fine in all of them.
Note: Image element has to be displayed inline
or inline-block
and centered horizontally with text-align: center
(on wrapper element).
// ALL of the JS below is for demonstration purposes only
$(document).ready(function() {
$('a').click(function() {
$('body > div').toggleClass('overflow');
});
})
img {
margin: 0 -9999% 0 -9999%;
}
/* ALL of the CSS below is for demonstration purposes only */
body {
text-align: center;
font-family: verdana;
font-size: 10pt;
line-height: 20pt;
}
body>div {
margin: 0px auto;
width: 40%;
background-color: lightblue;
overflow: hidden;
}
img {
vertical-align: top;
}
.overflow {
overflow: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>40% wide div [<a href="#">toggle overflow</a>]
<div>
<img src="http://via.placeholder.com/400x200" />
</div>
400px wide image
</div>