【问题标题】:Make element centered: margin-right not working使元素居中:margin-right 不起作用
【发布时间】:2022-11-14 23:19:24
【问题描述】:

我有一个 HTML 输入元素。我希望元素位于中心,但由于右边距不起作用,元素稍微偏右。 box-sizing: border-box; 无法解决问题。

我的代码

body {
  margin: 0;
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  margin: 40px;
  padding: 10px;
}

input {
  border-style: solid;
  border-color: #5f9341;
  border-width: 2px;
  width: 100%;
  box-sizing: border-box;
}
<html>

<head>
  <link rel="stylesheet" href="css/index.css">

  <script src="js/index.js"></script>
</head>

<body>
  <input type="text" id="input-el">
  <button id="input-btn">SAVE INPUT</button>
</body>

</html>

【问题讨论】:

标签: html css


【解决方案1】:

您可以将输入包装在带有 flex 显示的 div 中,并将该 div 的 align-items 设置为 center 以使其水平居中,并将 flex-direction 设置为 column 以便按钮和输入位于同一列中。

body {
  box-sizing: border-box;
  margin: 0;
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  margin: 40px;
  padding: 10px;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

input {
  border-style: solid;
  border-color: #5f9341;
  border-width: 2px;
  width: 100%;
  margin: 0;
}
<html>

<head>
  <link rel="stylesheet" href="css/index.css">

  <script src="js/index.js"></script>
</head>

<body>
  <div class="flex">
    <input type="text" id="input-el">
    <button id="input-btn">SAVE INPUT</button>
  </div>
</body>

</html>

【讨论】:

    【解决方案2】:

    margins添加对于百分比宽度,输入的总宽度变为 100% 加上 80px(左右各 40px)。

    如果您需要该边距,您可以将此值用作输入元素的widthwidth: calc(100% - 80px);,即 100% 宽,但减去左右边距:

    body {
      margin: 0;
      padding: 10px;
      font-family: Arial, Helvetica, sans-serif;
    }
    
    * {
      margin: 40px;
      padding: 10px;
    }
    
    input {
      border-style: solid;
      border-color: #5f9341;
      border-width: 2px;
      width: calc(100% - 80px);
      box-sizing: border-box;
    }
    <html>
    
    <head>
      <link rel="stylesheet" href="css/index.css">
    
      <script src="js/index.js"></script>
    </head>
    
    <body>
      <input type="text" id="input-el">
      <button id="input-btn">SAVE INPUT</button>
    </body>
    
    </html>

    【讨论】:

      【解决方案3】:

      你让 width:100% plus margin:40px 这使得元素无法居中。

      你应该取 width:80% 并设置 margin:auto;它将元素本身居中。 知道保存按钮应该在哪里也很重要? 你的目标需要明确。

      【讨论】:

        猜你喜欢
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2014-10-24
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        相关资源
        最近更新 更多