【问题标题】:How to make height equal width with css [duplicate]如何使用css使高度等于宽度[重复]
【发布时间】:2013-09-27 14:24:44
【问题描述】:

如何用 css 使高度等于宽度。

我有这样的 HTML:

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

现在,我想让a 元素的高度等于宽度(35%)。我怎样才能做到这一点?谢谢你的帮助。

【问题讨论】:

  • 您的意思是要按比例调整它的大小?
  • 他希望高度等于宽度,当宽度是百分比时。
  • 好吧,我可以把高度:auto...但我会检查一些东西..:P

标签: javascript html


【解决方案1】:

我知道了:

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

【讨论】:

  • 这根本没有做他想做的任何事情,jsfiddle.net/wGszc/1,内部元素的宽度和高度不同,您只是简单地使父元素具有相同的高度宽度。
  • 如果父元素具有相同的高度和宽度,并且您仅指定:这就是解决方案!还是不行?
  • 您缺少内容 css .content { position: absolute;顶部:0;左:0;底部:0;右:0; } 无论如何,这是一个重复的问题:stackoverflow.com/questions/5445491/…
【解决方案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 Demo

【讨论】:

  • 他有javascript标签
  • 还有标题:'with css',好吧,我会等着回答.. :P 你用 js 和我用 CSS... :P
  • 好吧。我正在寻找这个。非常感谢帕特里克·埃文斯。
  • 第二部分有错误,编辑解决。
  • Ikillnukes。对不起。只有css不能解决这个问题。感谢所有建议。
猜你喜欢
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2017-04-24
  • 2011-07-23
  • 1970-01-01
  • 2012-09-07
相关资源
最近更新 更多