垂直对齐响应宽度和高度图像

时间:2016-05-27 10:20:49

标签: css css3

我有一个div,它将根据屏幕大小改变宽度。我还希望div的高度调整到最大高度的图像,然后隐藏任何溢出的图像。

到目前为止,我只能使用绝对定位来居中图像,但这意味着我还必须包含相同大小的占位符图像,以便div更改高度:



#test {
  max-height: 400px;
  width: 50%;
  overflow: hidden;
  position: relative;
}
#test .test-image {
  width: 100%;
}
#test .vertical-align {
  left: 0;
  top: 50%;
  position: absolute;
  transform: translateY(-50%);
}

<div id="test">
  <!-- this is a placeholder to make the div height expand / contract depending on the width -->
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image">
  
  <!-- this is the vertically aligned image -->
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image vertical-align">
</div>
&#13;
&#13;
&#13;

有没有办法使用相对定位来做到这一点,所以我不需要包含占位符图像?

我想到了以下但它似乎没有用,因为它似乎只是将图像移回到它开始的位置并从底部裁剪而不是居中:

&#13;
&#13;
#test {
  max-height: 400px;
  width: 50%;
  overflow: hidden;
  position: relative;
}
#test .test-image {
  width: 100%;
}
#test .vertical-align {
  margin-top: 50%;
  position: relative;
  transform: translateY(-50%);
}
&#13;
<div id="test">
  <!-- this is the vertically aligned image -->
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image vertical-align"> 
</div>
&#13;
&#13;
&#13;

纯css有可能吗?请仅发布css解决方案 - 没有js答案。

由于

更新

我已经设法弄清楚为什么绝对有效,但相对没有 - 当绝对时,top:50%是父div的50%,而当相对时,{{1是图像高度的50%,这就是为什么翻译只是将它移回到它的起始位置。

所以我猜任何解决方案都是基于在应用变换之前将图像向下移动父项高度的50%。我在父母身上玩过填充物,但似乎无法使用

1 个答案:

答案 0 :(得分:5)

我找到了一个flex的解决方案,希望你发现它很有用:

&#13;
&#13;
#test {
  max-height: 400px;
  width: 50%;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow:hidden;
}

#test .test-image {
  width: 100%;
}
&#13;
<div id="test">
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image">
</div>
&#13;
&#13;
&#13;

<强>更新

我只是通过添加一个额外的div使它在IE 11中工作。也许这对你来说还不够,但我花了我所有的资源。

&#13;
&#13;
#container {
  display: flex;
}

#test {
  max-height: 400px;
  overflow: hidden;
  width: 50%;
  align-items: center;
  align-content:center;
  display: flex;
}

#test .test-image {
  width: 100%;
}
&#13;
<div id="container">
  <div id="test">
    <img src="http://lorempixel.com/800/800/sports/1" class="test-image">
  </div>
</div>
&#13;
&#13;
&#13;

相关问题