首页 > 解决方案 > 如何写一个始终位于屏幕中心并接触较短边缘的正方形?

问题描述

任务是绘制一个始终位于屏幕中心的正方形,并且左右或顶部或底部边缘始终位于屏幕边缘。如果我们知道屏幕方向,这很容易。

如果是纵向:(我设置了“屏幕”,实际正方形的高度和宽度都是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 想法吗?

标签: htmlcss

解决方案


你需要使用max-widthand 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>


推荐阅读