I have several images inside a container and I would like the images to be centered horizontally when the browser is resized. Currently, images align with the left edge like left: 0
, I want them to overflow outside the left and right edge if container is narrower than the image. I thought margin: 0 auto
would work. But it seems it doesn't. Basically this is what I want:
HTML:
<div class="container-fluid main-slide">
<div class="mask"></div>
<div class="cycle-slideshow" style="position: relative;">
<img src="/img/1.jpg" style="margin: 0 auto; min-width:100%; position: absolute; top:50%; transform: translateY(-30%);display:block;">
<img src="/img/2.jpg" style="margin: 0 auto; min-width:100%; position: absolute; top:50%; transform: translateY(-30%);display:block;">
<img src="/img/3.jpg" style="margin: 0 auto; min-width:100%; position: absolute; top:50%; transform: translateY(-30%);display:block;">
<img src="/img/4.jpg" style="margin: 0 auto; min-width:100%; position: absolute; top:50%; transform: translateY(-30%);display:block;">
</div>
</div>
CSS:
.main-slide{
height:520px;
width:100%;
max-width:1920px;
padding:0;
margin:0 auto;
overflow:hidden;
position: relative;
}
The following trick will center an image horizontally even if that requires pushing the left side outside the container.
.cycle-slideshow {
position: relative;
/* for testing */
margin: 0 auto;
border: 10px solid #FC0;
width: 200px;
height: 200px;
}
.cycle-slideshow img {
position: absolute;
top: 0;
/* fill vertically */
width: auto;
height: 100%;
/* center horizontally */
left: -1000px;
right: -1000px;
margin-left: auto;
margin-right: auto;
/* for testing */
z-index: -1;
}
<div class="container-fluid main-slide">
<div class="cycle-slideshow">
<img src="http://dummyimage.com/800x200/000/fff">
<img src="http://dummyimage.com/600x200/000/fff" style="display: none;">
<img src="http://dummyimage.com/400x200/000/fff" style="display: none;">
<img src="http://dummyimage.com/200x200/000/fff" style="display: none;">
</div>
</div>
<!-- cycle plugin will cycle the images one by one -->