2

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.

2 Answers 2

5

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Do you need to use js for that ?
@wadie not, but I am answering the question why
Sure, just wanted to make sure I wasn't missing anything. Thanks!
1

You can just use the same calc for the height

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.