Responsively change div size keeping aspect ratio(响应更改 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 大小保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:响应更改 div 大小保持纵横比
基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
