插件窝 干货文章 如何用CSS弹性布局实现一个在不同屏幕尺寸下都能保持正方形的骰子?

如何用CSS弹性布局实现一个在不同屏幕尺寸下都能保持正方形的骰子?

骰子 span width dice 275    来源:    2025-03-25

使用CSS弹性布局实现响应式正方形骰子

要实现一个在不同屏幕尺寸下都能保持正方形的骰子,我们可以结合CSS弹性布局(Flexbox)和宽高比技术。以下是完整的解决方案:

方法一:使用padding百分比技巧

<div class="dice-container">
  <div class="dice">
    <!-- 骰子点数可以通过伪元素或子元素实现 -->
    <span class="dot"></span>
    <!-- 更多点数... -->
  </div>
</div>
.dice-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px; /* 可根据需要调整 */
}

.dice {
  position: relative;
  width: 30%; /* 根据需要调整百分比 */
  height: 0;
  padding-bottom: 30%; /* 与width相同值保持正方形 */
  background-color: white;
  border: 2px solid #333;
  border-radius: 10%;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);

  /* 弹性布局用于排列点数 */
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-content: space-around;
}

/* 骰子点数样式 */
.dot {
  width: 20%;
  height: 20%;
  background-color: #333;
  border-radius: 50%;
}

方法二:使用aspect-ratio属性(现代浏览器支持)

.dice {
  width: 30vmin; /* 使用视口较小尺寸的单位 */
  aspect-ratio: 1/1; /* 强制宽高比1:1 */
  background-color: white;
  border: 2px solid #333;
  border-radius: 10%;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);

  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-content: space-around;
}

完整骰子实现示例

以下是实现一个完整骰子(6点)的代码:

<div class="dice dice-six">
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
</div>
.dice {
  width: 30vmin;
  aspect-ratio: 1/1;
  background-color: white;
  border: 2px solid #333;
  border-radius: 10%;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);
  padding: 10%;

  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.dot {
  width: 22%;
  height: 22%;
  background-color: #333;
  border-radius: 50%;
}

/* 6点骰子特定布局 */
.dice-six {
  flex-direction: column;
  justify-content: space-between;
}

.dice-six .dot-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

响应式调整

如果需要在不同尺寸下调整骰子大小,可以使用媒体查询:

@media (max-width: 600px) {
  .dice {
    width: 40vmin;
  }
}

@media (min-width: 1200px) {
  .dice {
    width: 20vmin;
  }
}

这种方法确保了骰子始终是正方形,并且能够适应不同屏幕尺寸。使用vmin单位或padding百分比技巧都能很好地实现这一目标。