html - 如何写一个始终位于屏幕中心并接触较短边缘的正方形?
问题描述
任务是绘制一个始终位于屏幕中心的正方形,并且左右或顶部或底部边缘始终位于屏幕边缘。如果我们知道屏幕方向,这很容易。
如果是纵向:(我设置了“屏幕”,实际正方形的高度和宽度都是100vw)
.screen{
width: 200px;
height: 400px;
border: 1px solid black;
display: flex;
}
.square{
background-color: red;
width: 200px;
height: 200px;
margin: auto;
}
<div class="screen">
<div class="square"></div>
</div>
如果横向:
.screen{
width: 100vw;
height: 100vh;
border: 1px solid black;
display: flex;
}
.square{
background-color: red;
width: 100vh;
height: 100vh;
margin: auto;
}
<div class="screen">
<div class="square"></div>
</div>
但是我们不知道屏幕方向,也不能使用 JavaScript。你有任何解决问题的唯一 CSS 想法吗?
解决方案
你需要使用max-width
and max-height
。
这样,无论是横向屏幕还是纵向屏幕,正方形都将始终适合屏幕。
.square {
width: 100vw;
height: 100vw;
max-width: 100vh;
max-height: 100vh;
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
background: red;
}
body {
margin: 0;
}
<div class="square"></div>
推荐阅读
- python - 是否有在 Python 中增加时间戳的函数
- android - getStableInsetTop() 总是返回 0?
- c - LPC2148 UART中断
- react-native - 异步/等待函数返回 _40: 0, _65: 0, _55: null, _72: null
- javascript - 如何将 JavaScript 对象文字从 Node 后端发送到浏览器前端?
- javascript - 在节点红色中将 Int 数转换为二进制数
- typo3 - 大文件的渲染类型输入链接,无需复制文件
- javascript - 将 .ics 文件提供给 webcal:// 而不是通过浏览器下载
- mysql - Mysql Sum 来自多维的数据
- angular - 如何根据语言更改 InputTextbox 标签?