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

标签 html css 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

最佳答案

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

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

Updated Fiddle that uses cycle plugin

关于html - 在容器中水平居中宽图像,必要时向左/右裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928454/

相关文章:

javascript - 触发 Mouseout 事件取决于窗口大小

javascript - jquery 将内容锚定到某个点

jquery - 带有 MouseOver Zoom 的垂直旋转木马

c# - 在同一行 2 上对齐 html 输入

javascript - 使用jquery从字符串中获取元素

html - 我怎样才能使我的表格居中? - HTML 和 CSS

javascript - 无法为每次迭代隐藏 div,并希望隐藏正在显示的边框

css - 在 IE8 上将宽度设置为 <option>

javascript - 触发高度计算 - jQuery Cycle2

javascript - 在 jQuery Cycle2 中定位下一张幻灯片