响应更改 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>
相关文章