保持具有动态高度的 div 的纵横比 [英] Maintain aspect ratio of a div with dynamic height
问题描述
我想通过纯 CSS 创建一个方形 div,它的 height
是动态的,它的 width
将根据 height 缩放
.
正如我们在下面的代码段中看到的,container
高度是动态的,基于它的内容.红色的 square
占据 container
的整个高度,宽度应该等于 height
.
我知道我们可以 根据宽度保持 div 的纵横比 但是当 height
是 dynamic 时,我找不到方法.
任何帮助,将不胜感激!非常感谢!
注意:高度是动态的,所以使用vh
的解决方案没有用,snipet 只是一个游乐场.
#container {宽度:400px;填充:20px;边框:纯 1px 黑色;位置:相对;}.正方形 {位置:绝对;顶部:0;右:0;底部:0;背景颜色:红色;宽度:100px/*嗯,它只是一个虚拟值*/}
<div class="内容">我是动态内容<div class="square"></div>
这是另一种解决方案:
我们可以在主 .square
div 内创建一个内部 div 继承其父高度.
然后,如果我们旋转那个内部 div,它的高度现在变成了它的宽度.所以此时我们要做的就是隐藏父 div 的溢出,并应用一些翻译使其在正确的位置结束.
#container {宽度:400px;填充:20px;边框:纯 1px 黑色;位置:相对;}.正方形 {位置:绝对;顶部:0;右:0;底部:0;溢出:隐藏;指针事件:无;}.square>div {背景颜色:红色;变换:旋转(-90度)平移(100%,0%);宽度:100vw;高度:100%;变换原点:100% 100%;}
<div class="内容"><文本区域>我是动态内容</textarea><div class="square"><div></div>
I wanted to create a square div by pure CSS what it's height
is dynamic and it's width
will scale base on height
.
As we can see in the snipet below, the container
height is dynamic base on its content.
The red square
take full height of the container
and the width should be equal height
.
I know we can maintain aspect ratio of a div base on its width but i can not find a way when the height
is dynamic.
Any help would be appreciated! Thanks so much!
Note that: The height is dynamic so the solution with vh
did not work and the snipet is just a playground.
#container {
width: 400px;
padding: 20px;
border: solid 1px black;
position: relative;
}
.square {
position: absolute;
top: 0;
right: 0;
bottom: 0;
background-color: red;
width: 100px /*Hmm its just a dummy value*/
}
<div id="container">
<div class="content">
I'm a dynamic content
</div>
<div class="square"></div>
</div>
Here is one other solution:
We can make an inner div inside the main .square
div inherits its parent height.
Then, if we rotate that inner div, its height now becomes its width. So all we've got to do at this point, is to hide the overflow from the parent div, and apply some translation so it ends at the correct position.
#container {
width: 400px;
padding: 20px;
border: solid 1px black;
position: relative;
}
.square {
position: absolute;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
pointer-events: none;
}
.square>div {
background-color: red;
transform: rotate(-90deg) translate(100%, 0%);
width: 100vw;
height: 100%;
transform-origin: 100% 100%;
}
<div id="container">
<div class="content">
<textarea> I'm a dynamic content</textarea>
</div>
<div class="square">
<div></div>
</div>
</div>
这篇关于保持具有动态高度的 div 的纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!