在容器中水平居中放宽图像,必要时左/右裁剪

时间:2014-11-14 10:58:46

标签: html css css3 jquery-cycle2

我在容器中有几个图像,我希望在调整浏览器大小时图像水平居中。目前,图像与左边缘对齐,如left: 0,如果容器比图像窄,我希望它们溢出左右边缘。我以为margin: 0 auto会起作用。但它似乎没有。基本上这就是我想要的:

enter image description here

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

FIDDLE

2 个答案:

答案 0 :(得分:2)

以下技巧会使图像水平居中,即使需要将左侧推向容器外。

&#13;
&#13;
.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;
}
&#13;
<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 -->
&#13;
&#13;
&#13;

Updated Fiddle that uses cycle plugin

答案 1 :(得分:0)

这是你的小提琴;我想这就是你要找的东西。 http://jsfiddle.net/qo625xkb/

刚刚为你的imgs添加了一个幻灯片类。和...

<div class="container-fluid main-slide">
  <div class="mask"></div>
  <div class="cycle-slideshow" style="position: relative;">
  <img class="slide" src="http://placekitten.com/g/200/300" />      
  <img class="slide" src="http://placekitten.com/g/200/300"  />      
  <img class="slide" src="http://placekitten.com/g/200/300" />      
  <img class="slide" src="http://placekitten.com/g/200/300" />
</div>

对整个容器,中心填充采取了不同的方法。

.main-slide{
    height:520px; 
    max-width:1920px;
    padding:0;  
    overflow:hidden;
    position: relative;
    border: 2px solid green;
}
.slide {
    position: absolute;
    min-height: 100%;
    min-width: 100%;
    transform: translate(-50%, -50%);
    margin-left: 50%;
    margin-top: 50%;
}