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.
source to share
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.
source to share
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>
source to share