根据宽度和高度保持纵横比
问题描述:
是否可以在视口中放置一个正方形 div
并使其居中并始终保持其根据宽度和高度的纵横比?
It is possible to fit and center a square div
in the viewport and always maintain it's aspect ratio according to width and height?
要求:
- 只有 CSS
- 无论视口的方向(横向或纵向)如何,正方形的大小都必须适应视口的最小尺寸(宽度或高度).
- 正方形必须在视口中水平和垂直居中
示例:
答
要在视口中根据宽度和高度保持 div 的纵横比,您可以使用一个 HTML 标签:
To maintain the aspect ratio of a div according to width and height in the viewport, you can use one HTML tag with:
-
vmin 用于调整大小的单位:
vmin 视口高度和宽度之间最小值的 1/100.
(来源:MDN)
- vmin units for the sizing :
position: absolute
和 margin: auto;
用于居中vmin 1/100th of the minimum value between the height and the width of the viewport.
(source : MDN)
DEMO(将窗口高度和宽度调整为看到它在行动)
position: absolute
and margin: auto;
for the centering- 根据宽度和高度 保持纵横比
- 水平和垂直保持在视口中心
- 永远不会溢出视口
vmin
单位由 IE10+ (canIuse) 支持以支持 IE9,您需要像这样使用 vm
单位而不是 vmin
的回退:
- keeps it's aspect ratio according to width and height
- stays centered in viewport horizontaly and verticaly
- never overflows the viewport
vmin
units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback with vm
units instead of vmin
like this :
完整代码:
任何你想要的内容
<div>whatever content you wish</div>