How to make the height of a dynamically sized <div> equal to the width

I have a div whose width is a percentage of the width of its container. My question is how can I guarantee that the height is the same pixel length as the width, given that the container is not a square (so I can't just set the percentage of height to the same amount as the width). Also, I would rather have a pure CSS solution and not use offsetWidth

, clientWidth

or other similar properties in JavaScript.

Example:

<div style="width:45%;background-color:blue">My Content!</div>

      

Thank.

+3


source to share


3 answers


I am afraid this is not possible with pure CSS.

If you don't mind, let me suggest a jQuery solution:

var $elem = ​$('div');
$(window).resize(function () {
    $elem.height($elem.width());
}).resize();

      



This will cause the height to be the same as the width, even if the window is resized. You can try it in the demo (try resizing):

I used jQuery because it helps a lot with how browsers handle element width and height.

+2


source


Maybe something like this: http://jsfiddle.net/gcvogxgL/



p { background-color: red; overflow: hidden; display: inline-block;}
p:before{content: ""; display: block; float: left; margin-top: 100%; }
p:after{ clear: both; content: ""; display: block; height: 1px;
margin-top: 100%; position: absolute; top: 0; }
      

<p>This is short</p>
<p>This is a medium</p>
<p>This is a very long square</p>
      

Run code


+2


source


This is not possible with pure CSS. Using a tiny piece of Javascript, this becomes very easy.

$("#mydiv").css("height", $("#mydiv").css("width"));​

      

0


source







All Articles