背景图片太长时,动画轮播居中问题解决

首先先新建一个html文件:

<body>
 <div class="father">
   <div class="son-left"></div>
   <div class="son"></div>
   <div class"son-right"></div>
</div>

先给他一个父元素div,然后给他三个孩子div,其实放图片的话一个div就够了,至于这里为什么有三个,是为了能让他在页面放大缩小时,轮播区域仍然居中,也就是说你看到的不一定是全部图片(放大倍数太大时,图片看不全),但一定是这个轮播图片的中间。

接着为他填充css样式,让他可以实现轮播

<style>
  .father{
     width:100%;
     height:420px;
     background-color:#f4f4f4;
}
 .son{
     width:1920px;
     height:100%;
     background-color:pink;
     margin:auto;
}
</style>

这是第一步,给父元素和子元素加样式,由于屏幕大小一般不太大,所以建议先缩放到最小,待完成后再查看正常情况下效果;

<style>
  .father{
     width:100%;
     height:420px;
     background-color:#f4f4f4;
}
 .son{
     width:1920px;
     height:100%;
     background-color:pink;
     margin:auto;
     background-repeat:no-repeat;
     background-position:center;
     animation:lunbo 15s linear infinite;

}

@keyframes lunbo{
   0%{background-image:url(./images/1.jpg);}
   20%{background-image:url(./images/2.jpg);}
   40%{background-image:url(./images/3.jpg);}
   60%{background-image:url(./images/4.jpg);}
   80%{background-image:url(./images/5.jpg);}
   100%{background-image:url(./images/1.jpg);}
}
</style>

这是为div.son加动画,让他实现轮播效果;
background-position是让背景图片一直在div.son中间的,不能省略;
background-repeat,因为我的div.son就是按照最大的图片宽高来设置的,所以可以省略,但如果你的有图片大小比较小,你就需要这个属性,让他看起来不会重复。
@keyframes是动画的写法。

但这个效果有个致命的bug,那就是当你将缩放比例调大的时候,div.son模块是按照屏幕视口最左端来铺展的,也就是说你的1920px图片是以屏幕最左侧为起点来铺展的,因此你在屏幕中看不到最中间的图片,这不是我们想要的效果,这是第一点。第二点是当你页面缩放比例变大时,将产生滚动条。下面将解决这两个问题:

<style>
  .father{
     width:100%;
     height:420px;
     background-color:#f4f4f4;
     display:flex;
}
 .son{
     width:1920px;
     height:100%;
     background-color:pink;
     margin:auto;
     background-repeat:no-repeat;
     background-position:center;
     animation:lunbo 15s linear infinite;

}

.son-left{
   flex:1;
   height:100%;
}
.son-right{
   flex:1;
   height:100%;
}

@keyframes lunbo{
   0%{background-image:url(./images/1.jpg);}
   20%{background-image:url(./images/2.jpg);}
   40%{background-image:url(./images/3.jpg);}
   60%{background-image:url(./images/4.jpg);}
   80%{background-image:url(./images/5.jpg);}
   100%{background-image:url(./images/1.jpg);}
}
</style>

首先让div.father变成伸缩盒,然后给左右两个div都加上flex:1;你也可以左右两个div写一个类,因为属性数值都一样,我这样写是为了看起来方便!这样他既不会产生滚动条,也实现了我们的需求。
最后效果是:
30%时页面
100%时页面

猜你喜欢

转载自blog.csdn.net/qq_39399252/article/details/81806285