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

Pet*_*ete 6 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%);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

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

#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%);
}
Run Code Online (Sandbox Code Playgroud)
<div id="test">
  <!-- this is the vertically aligned image -->
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image vertical-align"> 
</div>
Run Code Online (Sandbox Code Playgroud)

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

谢谢

更新

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

所以我想任何解决方案都是基于在应用变换之前将图像向下移动父项高度的50%.我在父母身上玩过填充,但这似乎不起作用

blo*_*nfu 5

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

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

#test .test-image {
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div id="test">
  <img src="http://lorempixel.com/800/800/sports/1" class="test-image">
</div>
Run Code Online (Sandbox Code Playgroud)

更新:

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

#container {
  display: flex;
}

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

#test .test-image {
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div id="test">
    <img src="http://lorempixel.com/800/800/sports/1" class="test-image">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)