将div宽度设置为高度的百分比

4
我正在尝试使用纯CSS设置.full_height_div元素的宽度,其宽度应相对于高度而不是与宽度相关联。这是因为父容器(.set_rectangle_height)已经是一个相对于页面宽度的高度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>

以下是不正确标记的示例:

incorrect layout

以下是我想要的正确布局:

correct layout

我知道我可以在JavaScript中查找蓝色正方形的百分比高度,然后将宽度设置为与此高度相等,但如果有一个纯CSS解决方案,那将非常方便。我将经常使用这种结构,因此不想编写代码来调整页面上所有div的大小。

1
是的。现在请删除您的踩。 - mulllhausen
让我为您调试一下:http://jsfiddle.net/Bushwazi/HSvW4/ - Jason Lydon
可能是通过CSS设置元素宽度基于高度的重复问题。 - John Mellor
2个回答

0

你需要使用JavaScript来实现。如果我理解正确,你想要一个完美的蓝色正方形。使用

var height = $('.square_set_width').height();
$('.square_set_width').css('width',height);

这是一个jsfiddle链接: http://jsfiddle.net/a8kxu/ 编辑:不要使用padding-bottom: 30%,而是使用height: 70%。这是另一个fiddle链接: http://jsfiddle.net/a8kxu/1/ 编辑 #2:抱歉,但你不能使用css来做这个。它的能力不足。

但是如果矩形必须随页面宽度缩放怎么办?我会更新我的示例代码,以免混淆。 - mulllhausen
你是什么意思说“矩形必须随页面宽度缩放”? - Thomas Lai
那你为什么不直接改变矩形的高度呢? - Thomas Lai
我将在5分钟内更新问题中的代码,以便更好地说明我的意思... - mulllhausen

-1

如果我理解你的意思正确

你可以做

#divID {
 width: 75%;
 margin-left: auto; // this is used to center the container
 margin-right: auto;// this as well
}

我认为你没有理解。请想象一个正方形在一个水平矩形内,就像我的代码示例中一样。 - mulllhausen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接