首页 > 解决方案 > 有没有一种 CSS 方法可以保证一个正方形在不滚动的情况下适合窗口?

问题描述

我可以很容易地在 JavaScript 中做到这一点,但想知道是否可以使用直接的 CSS:在窗口中保留一个方形 div,无论它是什么,都适合窗口大小。

我发现的任何解决方案都不能说明高度小于宽度。

从逻辑上讲,我想要的是,当窗口宽度小于高度时,给我一个该宽度的正方形。如果高度更小,那就给我一个那个大小的正方形。

我见过的最接近的解决方案使用以 vw 为单位测量的宽度和高度,但是当窗口非常宽和短时它不起作用。

标签: htmlcss

解决方案


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>


推荐阅读