html - 有没有一种 CSS 方法可以保证一个正方形在不滚动的情况下适合窗口?
问题描述
我可以很容易地在 JavaScript 中做到这一点,但想知道是否可以使用直接的 CSS:在窗口中保留一个方形 div,无论它是什么,都适合窗口大小。
我发现的任何解决方案都不能说明高度小于宽度。
从逻辑上讲,我想要的是,当窗口宽度小于高度时,给我一个该宽度的正方形。如果高度更小,那就给我一个那个大小的正方形。
我见过的最接近的解决方案使用以 vw 为单位测量的宽度和高度,但是当窗口非常宽和短时它不起作用。
解决方案
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>
推荐阅读
- python - 使用大数据集训练 TensorFlow BoostedTreesClassifier 时出现解码错误
- python - while 循环只经过一次
- firebase - 使用新查询重新访问时,已创建的嵌套 FutureBuilder 快照仍然存在
- r - 从宽到长:多列、两个时间点、两组
- reactjs - 在 React 中使用 ApolloClient 订阅 AppSync
- html - 如何通过链接转到 iframe 中的特定 pdf 页面?
- javascript - 在 Gatsby 中使用 useStaticQuery 填充数据的 SEO 效果
- pandas - 如何找出哪些管道朝向错误的方向
- php - 只应上传 jpg jpeg 和....照片
- vba - 获取错误 3075 条件表达式中的数据类型不匹配