I am currently working on a unique challenge where I aim to have a square element whose size is dependent on the height of the page. Basically, I want the width of the element to be linked to its height.
While I am aware that this can be achieved using the opposite technique, or by utilizing vh
, I have chosen to tackle this as a learning exercise.
My solution involves leveraging the aspect-ratio maintenance capability of img
tags for displayed images. Below is the HTML code snippet I came up with (the img
tag contains a 1x1px gif):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css"/>
</head>
<body>
<div class="circle-tree">
<div class="circle-tree-wrap">
<!-- Experimenting with img tag to create an element that adjusts width based on height -->
<img src="data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=">
<div class="circle-tree-content"></div>
</div>
</div>
</body>
</html>
In addition, here is the CSS code I wrote:
html, body {
padding: 0;
margin: 0;
width: 100%;
height: 100%; }
body {
background-color: #64d0ac; }
.circle-tree {
display: inline-block;
height: 100%;
width: 100%;
transform: translateX(50%); }
.circle-tree .circle-tree-wrap {
position: relative;
display: inline-block;
transform-style: preserve-3d;
height: 100%; }
.circle-tree .circle-tree-wrap .circle-tree-content {
position: absolute;
width: 100%;
height: 100%;
background-color: #fff;
top: 0;
left: 0;
transform: translateX(-50%); }
.circle-tree .circle-tree-wrap img {
height: 100%;
width: auto;
opacity: 0;
transform: translateX(-50%); }
This method successfully creates a square .circle-tree-content
upon initial page load. However, when resizing the browser window, the .circle-tree-wrap
does not dynamically adjust its width to match the new width of the img
element. A page reload corrects this issue temporarily. This behavior has been tested in both Chromium 43 and Firefox 38. While I understand that this approach may not be ideal for production purposes and I might opt for alternative solutions in the future (such as JS), I am intrigued by this particular quirk and would appreciate any insights from the community on why CSS calculations differ between resize events and page loads. Thank you for your help!