【问题标题】:How to make something a square using only percentage measurements如何仅使用百分比测量来制作正方形
【发布时间】:2018-09-24 18:48:36
【问题描述】:

我正在用 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% 的高度。有谁知道如何在不牺牲灵活性的情况下使这两个像素相同?

【问题讨论】:

    标签: html css percentage


    【解决方案1】:

    您可以使用视口单位vhvw,其中大小取决于窗口大小,因此它相对于窗口大小而非父元素大小是灵活的。

    .square {
      width: 10vw;
      height: 10vw;
      border: 1px solid black;
      margin: 50px;
    }
    <div class="square"></div>

    【讨论】:

      【解决方案2】:

      您可以使用百分比padding-bottom(或padding-top)来代替height

      #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>

      【讨论】:

        【解决方案3】:

        试试这个

        #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;
        }
        

        【讨论】:

          【解决方案4】:

          我建议不要使用百分比,而是使用 rem 单位,这也是响应式的。

          #ball {
            width: 1.5rem;
            height: 1.5rem;
            border: 1px solid #000;
            background: #f00;
          }
          <div id="ball"></div>

          【讨论】:

            猜你喜欢
            • 2022-08-09
            • 2023-01-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多