【发布时间】:2013-03-13 01:15:36
【问题描述】:
我正在尝试使用纯 css 设置 .full_height_div 元素的宽度,基于它的高度。它必须是相对于高度的宽度,而不是相对于宽度的高度。原因是父容器(.set_rectangle_height)已经是一个高度相对于页面宽度的 div。显然,随着页面大小的调整,页面上的divs 将调整大小,因此我无法在px 中为.full_height_div 子设置固定宽度。
所以.rectangle 和.set_rectangle_height 构成了父容器,其宽度占页面的百分比,高度相对于该宽度。有关此方法的说明,请参阅here。
但问题是,然后我想在父级内放置一个 div,其中 height: 100% 和相对于该高度的宽度。目标是我将能够更改浏览器窗口的大小,并且所有内容都将保持其纵横比。
.rectangle
{
position: relative;
width: 30%;/*the outermost div is always a % of the page
width, even while resizing*/
display:inline-block;
background-color: green;
}
.set_rectangle_height
{
padding-bottom: 30%;/*this sets the height of the outermost div
to a ratio of 1:3*/
position: relative;
float: left;
width: 100%;
height: 100%;
}
.full_height_div/*this is the div that i want to have a width relative
to its height*/
{
height: 100%;
width: 20px;/*i will delete this once .square_set_width is working*/
position: absolute;
background-color: red;
}
.square_set_width
{
display: inline-block;
padding-left: 100%; /*i want to use something like this line to set
the width of this div to be equal to .full_height_div's height - ie a 1:1 aspect
ratio, but padding-left does not work :( */
position: relative;
height: 100%;
background-color: blue;
}
<div class='rectangle'>
<div class='set_rectangle_height'>
<div class='full_height_div'>
<div class='square_set_width'></div>
</div>
</div>
</div>
所以,这就是上面错误标记的样子:
这就是我想要的样子:
我知道我可以在 javascript 中找到蓝色正方形百分比高度,然后将宽度设置为等于这个高度,但是如果有一个纯 css 修复来解决我正在尝试做的事情,那将非常方便。我会经常使用这种结构,我真的不想编写代码来调整页面上所有 div 的大小。
【问题讨论】:
-
是的。现在请删除您的反对票
-
让我为你摆弄一下:jsfiddle.net/Bushwazi/HSvW4
标签: css aspect-ratio