Jack
Jack

Reputation: 1999

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.

Upvotes: 2

Views: 2131

Answers (2)

Temani Afif
Temani Afif

Reputation: 272648

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>

Upvotes: 5

arieljuod
arieljuod

Reputation: 15838

You can just use the same calc for the height

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

Upvotes: 1

Related Questions