HTML&CSS-将图像轮播置于其容器的中心

时间:2018-09-19 11:27:16

标签: javascript jquery html css

我创建了一种图像轮播效果,但想尝试弄清楚如何将其置于容器的中心。

不确定是否可以将溢出隐藏起来,但任何建议或解决方法将不胜感激。

function slide(){
  var first = $('.slider_img').first();
  first.animate({opacity: '0', width: '0px'}, function() {
    first.appendTo('#slider').css({opacity: '1', width: 'auto'});
  });
  var slider_timeout = setTimeout(function(){slide()} , 3000);
}
slide();
#slider_container{
  position:relative;
  width:80%;
  height:50px;
  background-color:#fff;
  box-shadow:0px 0px 10px 0px rgba(0,0,0,0.5);
  overflow:hidden;
}
#slider{
  /* center */
}
#slider img{
  display:inline-block;
  margin:0px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="slider_container">
  <div id="slider">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=1">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=2">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=3">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=4">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=5">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=6">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=7">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=8">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=9">
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

喜欢吗?此版本将Flexbox与justify-content: center;

一起使用

function slide(){
  var first = $('.slider_img').first();
  first.animate({opacity: '0', width: '0px'}, function() {
    first.appendTo('#slider').css({opacity: '1', width: 'auto'});
  });
  var slider_timeout = setTimeout(function(){slide()} , 3000);
}
slide();
#slider_container {
  position: relative;
  width: 80%;
  height: 50px;
  background-color: #fff;
  box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.5);
  overflow: hidden;
}

#slider {
  display: flex;
  justify-content: center;
}

#slider img {
  flex-shrink: 0;
  margin: 0px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="slider_container">
  <div id="slider">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=1">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=2">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=3">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=4">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=5">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=6">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=7">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=8">
    <img class="slider_img" src="https://via.placeholder.com/100x50?text=9">
  </div>
</div>