【问题标题】:centering multiple absolute divs居中多个绝对 div
【发布时间】:2017-03-26 21:28:15
【问题描述】:

我有一个关于水平居中多个绝对 div 的问题。我有一个包含四个子 div 的相对父 div。我希望它们均匀居中。有没有办法让四个 div 居中然后添加一次?还是必须一一定位?我现在拥有的是当我将 div 定位为绝对位置时。当它们居中时,它们会相互堆叠。

感谢您的宝贵时间。

【问题讨论】:

标签: html css css-position


【解决方案1】:

您可以为您的子divs 定义一个div 并使用display: flex

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

boxes {
  margin-top: 25px;
  width: 100%;
  position: relative;
  text-align: center;
}
.eq {
  display: flex;
}
.box {
  width: 300px;
  max-height: 400px;
  min-height: 233px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  overflow-wrap: break-word;
  background-color: #fff;
  margin-right: 20px;
  ;
}
<div class="boxes">
  <div class="box">
    <h3>MyBMW Login</h3>
    <form class="" action="index.html" method="post">
      <input type="text" name="email" placeholder="Emailadres">
      <input type="password" name="password" placeholder="Wachtwoord">
    </form>
  </div>
  <div class="eq">
  <div class="box">
1
  </div>
  <div class="box">
2
  </div>
  <div class="box">
3
  </div>
  </div>
</div>

但是我不得不删除position: absolute。如果这不是您想要的,请提供更多详细信息。

【讨论】:

    【解决方案2】:

    把你的css改成这个,对我有用。

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    .boxes {
      position: absolute;
      background-color: #000;
      display: flex;
      margin-top: 25px;
      width: 100%;
      text-align: center;
    }
    
    .box {
      position: relative;
      width: 300px;
      max-height: 400px;
      min-height: 233px;
      padding: 15px;
      border: 1px solid #e6e6e6;
      overflow-wrap: break-word;
      background-color: #fff;
      margin-right: 20px;
    } 
    

    【讨论】:

    • 还可以添加align-items: middle;到父 div,并使用 margin: 0 auto;在中心对齐东西
    【解决方案3】:

    我不会将其设为绝对,这些 .box div 需要是相对的,您可以将 .boxes 设为“绝对位置”。

    https://jsfiddle.net/DamianToczek/3w50gj28/4/
    

    使 .boxes 成为绝对的,ID .box 不能是绝对的,你总是创建一个绝对的容器。如果你想让 .box 成为绝对的,你需要给它们另一个 id,比如 .box1 .box2 .box3,最好的选择总是一个包含“居中”项目的容器,容器是你的 .boxes:

    .boxes {
      width:100%;
      position:absolute;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-16
      • 2011-11-05
      • 2012-12-30
      • 2012-03-28
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      相关资源
      最近更新 更多