小编典典

响应式更改div大小,保持长宽比

css

当我给图像一个宽度或高度的百分比时,它只会保持其宽高比增长/缩小,但是如果我想与另一个元素具有相同的效果,是否可以完全使用百分比将宽度和高度绑定在一起?


阅读 600

收藏
2020-05-16

共1个答案

小编典典

您可以使用纯CSS来完成;无需JavaScript。这利用了padding-top百分比(相对于包含块的
width)的(有点违反直觉)事实。这是一个例子:

.wrapper {

  width: 50%;

  /* whatever width you want */

  display: inline-block;

  position: relative;

}

.wrapper:after {

  padding-top: 56.25%;

  /* 16:9 ratio */

  display: block;

  content: '';

}

.main {

  position: absolute;

  top: 0;

  bottom: 0;

  right: 0;

  left: 0;

  /* fill parent */

  background-color: deepskyblue;

  /* let's see it! */

  color: white;

}


<div class="wrapper">

  <div class="main">

    This is your div with the specified aspect ratio.

  </div>

</div>
2020-05-16