除了水平缩放之外,我还可以垂直缩放div及其内容吗



我有以下结构;

<body>
    <div id="splash">
      <img /> <!-- 512x512 -->
      <progress></progress>
      <img /> <!-- 512x512 -->
    </div>
</body>

这个css;

html, body {
    height: 100%;
}
#splash {
    max-height: 100%; /* does nothing */
}
#splash img {
    max-width: 100%;
    height: auto;
}

这导致整个div滚动以适应浏览器窗口的宽度。目前,这也会缩放div的高度,将内容推到浏览器窗口的底部边界以下。

是否也可以垂直缩放div,使其内容收缩,使其任何部分都不低于浏览器窗口的底部边界?

小提琴

body { 
    margin: 0;                /* 1 */
}
#splash { 
    height: 100vh;
    display: flex;            /* 2 */
    flex-direction: column;   /* 2 */
}
#splash > img {
    min-height: 0;            /* 3 */
    object-fit: contain;      /* 4  (also try `cover` value) */
    width: 100%;
}
progress {
    width: 100%;
}
<div id="splash">
    <img src="http://lorempixel.com/512/512/" />
    <progress></progress>
    <img src="http://lorempixel.com/512/512/" />
</div>

jsFiddle

注:

  1. 删除body元素上的默认边距(这可能导致滚动条(
  2. 建立垂直柔性容器
  3. 允许弹性项目缩小到超过内容大小
  4. 强制图像遵守纵横比(请注意,IE和Edge尚不支持object-fit。有关解决方法选项,请参阅此处的(

您的百分比不起作用,因为html没有定义的height。也使用100%

html, body, #splash {
  height: 100%;
  margin: 0;
}
#splash img {
  max-height: 48%;
  display: block;
  margin: 0 auto;
}
progress {
  display: block;
  box-sizing: border-box;
  width: 100%;
  height: 4%;
}
<div id="splash">
  <img src="http://lorempixel.com/512/512/" />
  <progress></progress>
  <img src="http://lorempixel.com/512/512/" />
</div>

使用calc()或flexbox可以实现更大的灵活性。

Michael_B的回答为我指明了正确的方向,但我最终选择了不依赖于支持object-fit的东西。

它需要将周围的div添加到progress中,并将图像的高度限制为我预计它们将占据的空间的估计值,在本例中为45%。

jsfiddle

html, body {
  height: 100%; 
  width: 100%;
  margin: 0;
}
#splash {
  height: 100%;
}
#splash img {
  max-width: 100%;
  max-height: 45%;
  width: auto;
}
<div id="splash">
    <img src="http://lorempixel.com/512/512/" />
    <div>
      <progress></progress>
    </div>
    <img src="http://lorempixel.com/512/512/" />
 </div>

最新更新