简体   繁体   中英

Issue getting CSS calc width with JS

I need to make a square element that is based off of the width of the screen. To set the height the same as the width, I tried using JS, but it seems to get it slightly wrong. Here is an example

 var square = document.getElementById('square'); square.style.height = square.clientWidth + 'px';
 #square { background-color: blue; width: calc(20vw - 16px); padding: 8px; }
 <div id="square">Element</div>

The blue "square" above is not square. Could any explain why? Instead of clientWidth , I've tried scrollWidth and offsetWidth with similar results. I haven't gotten style.width to give out a correct number either.

Even if you inspect, on Chrome, the blue square you get a number for the height and width that are close but still very different.

Two issues. First you need to consider the padding, so add box-sizing:border-box then you defined the width using vw unit, so you will have a sqaure only when you open the page the first time and never resize the browser.

 var square = document.getElementById('square'); square.style.height = square.clientWidth + 'px';
 #square { background-color: blue; width: calc(20vw - 16px); padding: 8px; box-sizing:border-box; }
 <div id="square">Element</div>

if you want a square that stay on window resize you need to use the same specified value and not the computed value in pixel ( How do you read CSS rule values with JavaScript? )

Or change the value on resize:

 var square = document.getElementById('square'); square.style.height = square.clientWidth + 'px'; window.onresize=function() { square.style.height = square.clientWidth + 'px'; };
 #square { background-color: blue; width: calc(20vw - 16px); padding: 8px; box-sizing:border-box; }
 <div id="square">Element</div>


As a side note you can consider CSS variable to specify the same value only once or check this : Maintain the aspect ratio of a div with CSS

 #square { --v:calc(20vw - 16px); background-color: blue; width: var(--v); height: var(--v); padding: 8px; box-sizing:border-box; }
 <div id="square">Element</div>

You can just use the same calc for the height

width: calc(20vw - 16px);
height: calc(20vw - 16px);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM