响应更改 div 大小保持纵横比 [英] Responsively change div size keeping aspect ratio

查看:33
本文介绍了响应更改 div 大小保持纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我给图像一个百分比宽度或高度时,它只会在保持其纵横比的情况下增长/缩小,但如果我想要与另一个元素相同的效果,是否可以使用百分比将宽度和高度联系在一起?

When I give an image a percent width or height only it will grow/shrink keeping its aspect ratio, but if I want the same effect with another element, is it possible at all to tie the width and the height together using percentage?

推荐答案

你可以使用纯 CSS 来做到这一点;不需要 JavaScript.这利用了(有点违反直觉的)事实,即 padding-top 百分比相对于包含块的宽度.这是一个例子:

You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that padding-top percentages are relative to the containing block's width. Here's an example:

.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>

这篇关于响应更改 div 大小保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆