Is there a CSS method of guaranteeing a square that fits in the window without scrolling?

Viewed 65

I can do this in JavaScript easily enough, but would like to know if it's possible with straight CSS: keep a square div in a window that fits within the window size regardless of what that is.

Any solutions I've found do not account for the height becoming less than the width.

Logically speaking what I want is, when the window width is less than the height, give me a square of that width. If the height is less, then give me a square of that size.

The closest solution I've seen uses a width and height measured in vw, but it does not work when the window is very wide and short.

1 Answers

I suggest using the vmin unit.

Source

From the viewport-percentage lengths documentation on MDN:

Viewport-percentage lengths define the value relative to the size of the viewport, i.e., the visible portion of the document. Viewport lengths are invalid in @page declaration blocks.

vmin
Equal to the smaller of vw and vh.

Example

Use the full page link to test it with the example in your browser.

body {
  /* So the whole viewport can be used by the square. */
  margin: 0;
}

#sqr {
  /* Uses the 'outer' (i.e. border-box) size when setting width and height. */
  box-sizing: border-box;
  width: 100vmin;
  height: 100vmin;
  background-color: red;
  border: yellow 10px solid;
}
<div id="sqr"><div>

Related