如何仅使用百分比测量值来制作正方形
How to make something a square using only percentage measurements
我正在 JavaScript 中编写乒乓球游戏,出于显而易见的原因,我需要球是正方形的。我使用的是百分比测量值,因此游戏适用于所有分辨率,但我想知道如何使用这些测量值使球成为正方形。
#ball{
position: absolute;
height: 1.5%;
width: 1.5%;
background-color: white;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
显然宽度的 1.5% 比高度的 1.5% 多很多。有谁知道如何在不牺牲灵活性的情况下使这两个像素相同?
试试这个
#ball {
position: absolute;
height: 1.5%;
width: 1.5%;
max-height: 1.5%;
max-width: 1.5%;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding: 38px 30px;
}
或在像素中使用
#ball {
position: absolute;
height: 80px;
width: 80px;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
我建议使用 rem 单位,而不是使用百分比,它也具有响应性。
#ball {
width: 1.5rem;
height: 1.5rem;
border: 1px solid #000;
background: #f00;
}
<div id="ball"></div>
而不是 height
,您可以使用百分比 padding-bottom
(或 padding-top
):
#ball {
position: absolute;
width: 3.5%;
background-color: red;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding-bottom: 3.5%;
}
<div id="ball"></div>
您可以使用视口单位 vh
或 vw
,其中大小取决于 window 大小,因此它相对于 window 大小而不是父元素大小是灵活的。
.square {
width: 10vw;
height: 10vw;
border: 1px solid black;
margin: 50px;
}
<div class="square"></div>
我正在 JavaScript 中编写乒乓球游戏,出于显而易见的原因,我需要球是正方形的。我使用的是百分比测量值,因此游戏适用于所有分辨率,但我想知道如何使用这些测量值使球成为正方形。
#ball{
position: absolute;
height: 1.5%;
width: 1.5%;
background-color: white;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
显然宽度的 1.5% 比高度的 1.5% 多很多。有谁知道如何在不牺牲灵活性的情况下使这两个像素相同?
试试这个
#ball {
position: absolute;
height: 1.5%;
width: 1.5%;
max-height: 1.5%;
max-width: 1.5%;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding: 38px 30px;
}
或在像素中使用
#ball {
position: absolute;
height: 80px;
width: 80px;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
我建议使用 rem 单位,而不是使用百分比,它也具有响应性。
#ball {
width: 1.5rem;
height: 1.5rem;
border: 1px solid #000;
background: #f00;
}
<div id="ball"></div>
而不是 height
,您可以使用百分比 padding-bottom
(或 padding-top
):
#ball {
position: absolute;
width: 3.5%;
background-color: red;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding-bottom: 3.5%;
}
<div id="ball"></div>
您可以使用视口单位 vh
或 vw
,其中大小取决于 window 大小,因此它相对于 window 大小而不是父元素大小是灵活的。
.square {
width: 10vw;
height: 10vw;
border: 1px solid black;
margin: 50px;
}
<div class="square"></div>