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.

Hai Tien
  • 2,929
  • 7
  • 36
  • 55

2 Answers2

10

Well I have that:

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

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

Seazoux
  • 621
  • 1
  • 5
  • 28
  • this does not do anything at all what he wants, http://jsfiddle.net/wGszc/1/, the inner element is not same width and height, you have just simply made the parent element have same height width. – Patrick Evans Sep 22 '13 at 17:48
  • If the parent element has same height and width and you specified only with: that's the solution! Or not? – dash1e Feb 22 '14 at 15:11
  • 1
    you're missing the content css .content { position: absolute; top: 0; left: 0; bottom: 0; right: 0; } this is a duplicate question anyway: http://stackoverflow.com/questions/5445491/height-equal-to-dynamic-width-css-fluid-layout – Juan Jimenez Mar 03 '14 at 21:19
2

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.

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)+"%";

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.

JSFiddle Demo

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87