如何使用CSS使高度等于宽度

5

你的意思是要等比例调整大小吗? - Seazoux
1
当宽度为百分比时,他希望高度与宽度相等。 - Bart
好的,我可以把height:auto放进去... 不过我要检查一些东西.. :P - Seazoux
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

你可以根据自己的需求进行调整...

还有...在谷歌上搜一下也不会有坏处:https://www.google.com/search?q=make+height+iquals+to+width


这根本不是他想要的任何东西,http://jsfiddle.net/wGszc/1/,内部元素的宽度和高度并不相同,你只是简单地使父元素具有相同的高度和宽度。 - Patrick Evans
如果父元素具有相同的高度和宽度,并且您仅指定了“width”,那么这就是解决方案!或者不是吗? - dash1e
1
你缺少了内容css .content { position: absolute; top: 0; left: 0; bottom: 0; right: 0; }无论如何,这是一个重复的问题:https://dev59.com/t2035IYBdhLWcg3wZvFg - Juan Jimenez

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演示

1
他已经打了JavaScript标签。 - Patrick Evans
而标题是“使用CSS”,好吧,我会等待答案... :P 你用JS做了它,而我用CSS... :P - Seazoux
好的。我正在寻找这个。非常感谢Patrick Evans。 - Hai Tien
第二部分有错误,正在编辑以解决。 - Patrick Evans
Ikillnukes。抱歉,仅使用CSS无法解决此问题。感谢所有的建议。 - Hai Tien
没有任何问题。 - Seazoux

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