对象适合:在保持纵横比的同时包含

时间:2016-03-16 08:30:35

标签: css aspect-ratio

假设我有以下标记:

<div id='container'>
  <div id='content'>
  </div>
</div>

和css:

#container {
   width: 100%;   /* container fills window */
   height: 100%;
   max-width: 1000px;
}
#content {
  width: 100%;
  padding-top: 66%; /* (1.5:1 aspect ratio */
  object-fit: contain;
}

无论什么时候,这都有我想要的行为(即使没有object-fit) 浏览器宽高比小于1.5:1。我想#container 元素始终保持完全在视野中,同时也保持宽高比。

这在纯css中是否可行(我不介意添加额外的元素)?

我不想使用vwvh,因为容器的宽度受max-width限制。

1 个答案:

答案 0 :(得分:0)

看起来你想要这样的东西:

body {
  margin: 0;
}
#container {
  position: relative; /* Containing block for absolutely positioned descendants */
  float: left; /* Shrink-to-fit width */
  background: red;
}
#container > canvas {
  display: block; /* Avoids vertical-align problems */
  max-width: 100%; /* Like object-fit:contain (part 1) */
  max-height: 100vh; /* Like object-fit:contain (part 2) */
}
#content {
  position: absolute; /* Take it out of flow */
  top: 0; right: 0; bottom: 0; left: 0; /* Same size as containing block */
  overflow: auto; /* In case its contents are too big */
}
<div id='container'>
  <canvas width="1000" height="666"></canvas>
  <div id='content'> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non nulla augue. Vivamus hendrerit arcu id fermentum vehicula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed non efficitur eros. Mauris pulvinar tortor eros, vitae mollis est suscipit non. Sed accumsan mi vel odio sollicitudin sagittis. Curabitur euismod justo et lorem suscipit tempus.Fusce enim metus, maximus sed lacinia ut, ultrices eu arcu. Vivamus interdum ex ac justo pretium pulvinar. Integer ornare vulputate ligula nec imperdiet. Sed suscipit nisi metus. Aliquam massa ante, dapibus laoreet mauris et, dignissim malesuada urna. Vivamus eleifend pellentesque nisl vitae laoreet. Phasellus a fringilla mauris. Nunc condimentum dui est, eget lobortis ipsum feugiat dictum. Vivamus ultricies, nisi ac gravida luctus, leo augue pulvinar massa, sit amet dictum eros magna at justo. Vivamus eu felis a ipsum auctor imperdiet. Donec eget bibendum tortor. Pellentesque mollis, orci ac molestie mollis, mi eros commodo magna, ac rutrum tellus ipsum in tortor. Nulla vel dui egestas, iaculis felis id, iaculis sem.Vivamus vel varius magna. Vestibulum vulputate massa quis urna finibus rhoncus. Etiam varius in dui fermentum venenatis. In fermentum enim sed laoreet porta. Proin sit amet auctor sapien, eu dapibus nunc. Praesent malesuada leo nec libero interdum efficitur. Nulla ipsum est, tristique ut malesuada id, blandit at odio. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam ac ipsum tristique, feugiat justo eu, pellentesque odio.</div>
</div>

它使用canvas将width属性设置为所需的最大宽度,并使用宽高比给出的height属性。然后使用max-height: 100vhmax-width: 100%设置样式,以实现类似object-fit: contain的内容。

由于#containerheight: autofloat: left,因此其大小与画布相同。

然后,您可以在绝对定位的元素中添加一些内容,其大小与#container相同。