我正在尝试使用纯CSS设置
.full_height_div
元素的宽度,其宽度应相对于高度而不是与宽度相关联。这是因为父容器(.set_rectangle_height
)已经是一个相对于页面宽度的高度div。显然,随着页面的调整,页面上的将重新调整大小,因此我不能为
所以
但问题在于,我要在父元素中放置一个
以下是不正确标记的示例: 以下是我想要的正确布局: 我知道我可以在JavaScript中查找蓝色正方形的百分比高度,然后将宽度设置为与此高度相等,但如果有一个纯CSS解决方案,那将非常方便。我将经常使用这种结构,因此不想编写代码来调整页面上所有div的大小。
.full_height_div
子代设置固定的px
宽度。所以
.rectangle
和.set_rectangle_height
组成了父容器,其宽度为页面百分比,高度相对于此宽度。有关此方法的解释,请参见此处。但问题在于,我要在父元素中放置一个
height: 100%
并相对于此高度的宽度div。目的是我将能够改变浏览器窗口大小,一切都将保持其纵横比。
这里是我的失败尝试:.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的大小。