要创建一个始终保持正方形的骰子(无论容器大小如何变化),可以使用CSS的弹性布局(Flexbox)结合padding技巧。以下是完整的解决方案:
<div class="dice">
<div class="dot"></div>
<!-- 可以根据需要添加更多点 -->
</div>
.dice {
position: relative;
width: 30%; /* 可以是任意百分比或固定值 */
padding-top: 30%; /* 与width相同,确保正方形 */
background-color: white;
border: 2px solid black;
border-radius: 10%;
display: flex;
justify-content: center;
align-items: center;
}
.dot {
width: 20%;
height: 20%;
background-color: black;
border-radius: 50%;
}
.dice {
width: 30%; /* 可以是任意百分比或固定值 */
aspect-ratio: 1 / 1; /* 强制宽高比为1:1 */
background-color: white;
border: 2px solid black;
border-radius: 10%;
display: flex;
justify-content: center;
align-items: center;
}
<div class="dice dice-6">
<div class="column">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
<div class="column">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
.dice {
width: 100px; /* 可以调整大小 */
aspect-ratio: 1 / 1;
background-color: white;
border: 2px solid black;
border-radius: 10%;
padding: 10%;
display: flex;
justify-content: space-between;
}
.column {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.dot {
width: 20%;
height: 20%;
background-color: black;
border-radius: 50%;
}
要使骰子在不同屏幕尺寸下保持比例:
.dice {
width: 20vmin; /* 使用视口最小单位 */
height: 20vmin;
/* 或者 */
width: min(200px, 30vw);
height: min(200px, 30vw);
}
这些方法都能确保骰子始终保持正方形,无论容器大小如何变化。选择哪种方法取决于你的项目需求和浏览器兼容性要求。