2013-03-23 153 views
1

我试图根据其高度设置使用纯CSS的.full_height_div元素的宽度。它必须是宽度相对高度,而不是高度相对宽度。原因是父容器(.set_rectangle_height)已经是一个高度相对于页面宽度的div。显然,当页面大小调整时,页面上的div将会调整大小,所以我无法为.full_height_div孩子设置px的固定宽度。设置div宽度作为高度的百分比

因此,.rectangle.set_rectangle_height组成父容器,它具有作为页面百分比的宽度和相对于该宽度的高度。有关此方法的说明,请参见here

但问题是,然后我想把一个div放在父亲height: 100%和宽度相对于这个高度。目的是让我能够改变浏览器的窗口大小,一切都会保持其高宽比。

here is my failed attempt:

.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

I知道我可以在javascript中找到蓝色方块百分比高度,然后将宽度设置为等于此高度,但如果我正在尝试执行纯CSS修复,那将非常方便。我会很多地使用这个结构,我并不想去编写代码来调整我的页面上的所有div。

+0

是的。现在请删除您的downvote – mulllhausen 2013-03-23 03:23:59

+0

欣然删除。 – L0j1k 2013-03-23 03:25:25

+0

让我为你拨弄吧:http://jsfiddle.net/Bushwazi/HSvW4/ – 2013-03-23 03:41:22

回答

-1

如果我正确

理解你,你可以做

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

我不认为你已经理解了。根据示例中的代码想象一个水平矩形内的正方形。 – mulllhausen 2013-03-23 03:27:47

0

,你必须使用JavaScript为。如果我理解你,你想要一个完美的蓝色方块。使用

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

这里是一个的jsfiddle:http://jsfiddle.net/a8kxu/

编辑:与其做padding-bottom: 30%height: 70%代替。这里是另一个小提琴:http://jsfiddle.net/a8kxu/1/

编辑#2:对不起,但你不能使用CSS来做到这一点。它不够强大

+0

但是如果矩形必须与页面宽度一起缩放呢?我会更新我的示例代码,因为这可能会让人困惑...... – mulllhausen 2013-03-23 03:46:03

+0

你是什么意思“矩形必须与页面宽度成比例”? – 2013-03-23 03:49:31

+0

所以你为什么不改变矩形的高度? – 2013-03-23 03:53:47