2013-09-22 44 views
5

如何用css使高度等於寬度。如何用css使高度等於寬度

我有HTML這樣的:現在

<div style="width:900px;height:200px;"> 
<a style="display:block; float:left; width:35%; background:green"></a> 
</div> 

,我想使a元件相等的寬度(35%)的高度。我怎樣才能做到這一點?感謝您的幫助。

+0

你是說你想調整它的比例嗎? – Seazoux

+1

當寬度爲百分比時,他希望高度等於寬度。 – Bart

+0

嗯,我可以把高度:自動...但我會檢查一些..:P – Seazoux

回答

2

使用window.getComputedStyle得到計算寬度,然後進行計算以獲得與寬度相同的等效百分比。

HTML

<div class="someDiv" style="width:900px;height:200px;"> 
    <a class="someAnchor" style="display:block; float:left; width:35%; background:green"></a> 
</div> 

JS

var anchor = document.querySelector(".someDiv .someAnchor"); 
var astyle = window.getComputedStyle(anchor); 
anchor.style.height = astyle.width; //this will make it static though 

//to make it a percentage like width so it will expand and contract with resize of parent element 

var pstyle = window.getComputedStyle(anchor.parentNode); 
var pheight = parseInt(pstyle.height); 
var awidth = parseInt(astyle.width); 
anchor.style.height = ((awidth/pheight)*100)+"%"; 

注意,錨元素會比格高度明智更大,以保持它,你將不得不將其縮小父裏面。

JSFiddle Demo

+1

他只想要CSS ... – Seazoux

+1

他有javascript標籤: –

+0

標題:'與CSS',以及我會等待回答..:P你已經與js和我與CSS ...:P – Seazoux

9

嗯,我有一個:

HTML:

<div class='box'> 
    <div class='content'>Aspect ratio of 1:1</div> 
</div> 

CSS:

.box{ 
    background:#000; 
    position: relative; 
    width: 50%;  /* desired width */ 
} 
.box:before{ 
    content: ""; 
    display: block; 
    padding-top: 100%; /* initial ratio of 1:1*/ 
} 

的jsfiddle:http://jsfiddle.net/wGszc/

http://www.mademyday.de/css-height-equals-width-with-pure-css.html

你可以把它適應您的需求...

和...在谷歌搜索小不傷:https://www.google.com/search?q=make+height+iquals+to+width

+0

這不是解決方案。 –

+0

你可以適應它! – Seazoux

+0

這不會做任何他想做的事情,http://jsfiddle.net/wGszc/1/,內部元素不是相同的寬度和高度,你只是簡單地使父元素具有相同的高度寬度。 –