5

How to make height equal width with css.

I have HTML like that :

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

Now, I'd like to make height of a element equal width (35%). How can I do that? Thank your help.

4

2 回答 2

10

好吧,我有:

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

您可以根据自己的需要调整它...

并且...在 google 中进行一点搜索并没有什么坏处:https ://www.google.com/search?q=make+height+iquals+to+width

于 2013-09-22T17:26:24.100 回答
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)+"%";

请注意,锚元素将大于 div 高度,要将其保留在父元素中,您必须将其缩小。

JSFiddle 演示

于 2013-09-22T17:27:48.707 回答