【问题标题】:How do I center this div on the screen? The positioning seems to be off by a little bit [duplicate]如何让这个 div 在屏幕上居中?定位似乎有点偏离[重复]
【发布时间】:2021-12-23 09:00:12
【问题描述】:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      background-color: #7a64fa;
    }
    
    .container {
      background-color: #ffffff;
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
      padding-top: 75px;
      padding-right: 50px;
      padding-bottom: 75px;
      padding-left: 50px;
      border-radius: 10px;
    }
    
    label {
      font-size: 25px;
      font-family: "Lucida Console", "Courier New", monospace;
    }
    
    input {
      border-radius: 5px;
    }
    
    .ftm {
      display: inline-block;
    }
  </style>
  <meta charset="ISO-8859-1">
  <title>Feet to Meter</title>
</head>

<body>
  <div class="container">
    <div class="ftm">
      <label>Feet</label><br /> <input style="height: 40px;" type="number" name="feet">
    </div>
    <div class="ftm">
      <label>Meter</label> <br /> <input style="height: 40px;" type="number" name="meter">
    </div>
  </div>

</body>

</html>

我想看看为什么容器 DIV 不能完全居中在屏幕上。我试图调整容器的 css,但似乎无法让 div 保持在中心。它也可能与填充有关。

【问题讨论】:

  • Flex-box 对你来说是最好的和最容易的,但你也可以使用 translate 属性来居中

标签: html css


【解决方案1】:

看起来您正在尝试使用 div 居中

  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;

这不起作用,因为 div 的尺寸不是 100x200。改用相对变换:

  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

【讨论】:

    【解决方案2】:

    .container 类中删除边距

    margin-top: -50px; // remove
    margin-left: -100px;  // remove
    

    添加

    transform: translate(-50%, -50%);
    

    【讨论】:

      【解决方案3】:

      .container 中删除margin-left 并添加transform: translateX(-50%); 访问translate() by mdn了解更多关于css翻译的信息

            .container {
          background-color: #ffffff;
          position: fixed;
          top: 50%;
          left: 50%;
          transform: translateX(-50%);
          margin-top: -50px;
          /* margin-left: -100px; */
          padding-top: 75px;
          padding-right: 50px;
          padding-bottom: 75px;
          padding-left: 50px;
          border-radius: 10px;
        }
      

      【讨论】:

        猜你喜欢
        • 2021-06-11
        • 2015-08-16
        • 2013-02-04
        • 2015-07-11
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多