2013-03-23 169 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

相關問題