无论视口宽度如何,都将视图居中在视口中

时间:2018-05-30 11:01:05

标签: html css

我有一个图片幻灯片,我试图在视口中居中,无论视口的宽度如何。如果使用margin: auto;视口比图像宽,则可以轻松实现这一点,但是,当视口比图像窄时,如在纵向模式下的平板电脑上,图像会对着左边距而不是中心。

以横向模式为中心:

enter image description here

以纵向模式为中心:

enter image description here

这是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>

这是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;}

3 个答案:

答案 0 :(得分:1)

据我所知,无论屏幕尺寸是多少,您都希望图像显示在中央。为此,您可以尝试以下代码:

#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>

答案 1 :(得分:0)

您可以使用flexbox。但作为替代方案,您可以使用位置和负边距来知道高度和宽度:

position:absolute;
left:50%;
margin-left:-512px;
top:50%;
margin-top:-150px;

See it in action

答案 2 :(得分:0)

你可以在你的情况下使用flex吗?这取决于您需要支持哪些浏览器。你可以使用caniuse检查出来。 与此同时,这是一个样本

https://codepen.io/hellouniverse/pen/QxwNWv

我将一个图像垂直和水平居中以显示方式

#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>