Reputation: 3
I have an image slideshow that I am trying to centre in the viewport, regardless of the viewport's width. This is easily achieved if the viewport is wider than the image by using margin: auto;
, however, when the viewport is narrower than the image, like on a tablet in portrait mode, the image butts up against the left margin and does not centre.
Centred in landscape mode:
Centred in portrait mode:
This is the HTML:
<div id="slidebound">
<div class="slider">
<img src="images/slider/slide04.png" alt=""/>
<img src="images/slider/slide03.png" alt=""/>
<img src="images/slider/slide02.png" alt=""/>
<img src="images/slider/slide01.png" alt=""/>
</div>
</div>
This is the CSS:
#slidebound {
width: 100%;
height: 300px;
overflow: hidden;
}
.slider {
width: 1024px;
height: 300px;
overflow: hidden;
position: relative;
margin: 0 auto;
}
.slider img {
position: absolute;
animation: slider 32s infinite;
opacity: 0;
width: 100%;
height: auto;
}
@keyframes slider {25% {opacity: 1;} 40% {opacity: 0;}}
.slider img:nth-child(4) {animation-delay: 0s;}
.slider img:nth-child(3) {animation-delay: 8s;}
.slider img:nth-child(2) {animation-delay: 16s;}
.slider img:nth-child(1) {animation-delay: 24s;}
Upvotes: 0
Views: 160
Reputation: 515
As per i understand, you want your image to appear in center, no-matter what the screen size is. For this you can try below code:
#slidebound {
width: 100%;
height: 300px;
overflow: hidden;
display: flex;
justify-content: center;
}
.slider {
width: 1024px;
height: 300px;
overflow: hidden;
position: relative;
margin: 0 auto;
}
.slider img {
position: absolute;
animation: slider 32s infinite;
opacity: 0;
width: 100%;
height: auto;
}
@keyframes slider {25% {opacity: 1;} 40% {opacity: 0;}}
.slider img:nth-child(4) {animation-delay: 0s;}
.slider img:nth-child(3) {animation-delay: 2s;}
.slider img:nth-child(2) {animation-delay: 3s;}
.slider img:nth-child(1) {animation-delay: 4s;}
<div id="slidebound">
<div class="slider">
<img src="http://abload.de/img/a6aawu.jpg" alt=""/>
<img src="https://nxworld.net/example/css-image-hover-effects/pic01.jpg" alt=""/>
<img src="http://abload.de/img/a6aawu.jpg" alt=""/>
<img src="https://nxworld.net/example/css-image-hover-effects/pic01.jpg" alt=""/>
</div>
Upvotes: 1
Reputation: 3302
Are you ok in using flex for your case? It depends on what browsers you need to support. You can check it out using caniuse. In the meantime, here is a sample
https://codepen.io/hellouniverse/pen/QxwNWv
where I have centred one image both vertically and horizontally to show the way
#slidebound {
height: 100vh;
}
.slider {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
margin: 0 auto;
height: inherit;
}
<div id="slidebound">
<div class="slider">
<img src="https://naomisimson.com/wp-content/uploads/image-placeholder.jpg" alt="" />
</div>
</div>
Upvotes: 0