javascript 如何使用css使高度等于宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18946564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make height equal width with css
提问by Hai Tien
How to make height equal width with css.
如何使用css使高度等于宽度。
I have HTML like that :
我有这样的 HTML:
<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.
现在,我想让a
元素的高度等于宽度(35%)。我怎样才能做到这一点?谢谢你的帮助。
采纳答案by Patrick Evans
use window.getComputedStyle
to get the computed width, then do calculations to get the equvialent percentage that will make it the same size as the width.
用于window.getComputedStyle
获取计算出的宽度,然后进行计算以获取使其与宽度大小相同的等效百分比。
HTML
HTML
<div class="someDiv" style="width:900px;height:200px;">
<a class="someAnchor" style="display:block; float:left; width:35%; background:green"></a>
</div>
JS
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)+"%";
Note that the anchor element will be bigger than the div height wise, to keep it inside the parent you will have to scale it down.
请注意,锚元素将大于 div 高度,为了将其保留在父元素内,您必须将其缩小。
回答by Seazoux
Well I have that:
好吧,我有:
HTML:
HTML:
<div class='box'>
<div class='content'>Aspect ratio of 1:1</div>
</div>
CSS:
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/
JSFiddle:http : //jsfiddle.net/wGszc/
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
You can adapt it to your needs...
您可以根据自己的需要进行调整...
And...A little search in google doesn't hurt: https://www.google.com/search?q=make+height+iquals+to+width
而且......在谷歌中进行一点搜索并没有什么坏处:https: //www.google.com/search?q=make+height+iquals+to+width