【问题标题】:Position Absolute doesn't center block绝对位置不居中
【发布时间】:2016-11-11 00:02:25
【问题描述】:

我希望我的块位于页面的中心,但是在我设置 position: absolutemargin-leftmargin-right 之后,auto 不起作用。

.block1 {
  position:absolute;
  bottom:0;
  height: 336px;
  width: 1020px;
  margin-left: auto;
  margin-right: auto;
} 

是否可以同时拥有 position :absolute 和 center 块?

【问题讨论】:

  • 水平居中或垂直居中或两者兼而有之?

标签: html css block


【解决方案1】:

是的,如果您有固定宽度,请使用left: 50%margin-left: -halfWidth

.parent-block {
  position: relative;
  height: 200px;
  width: 100%;
  border: blue dotted 1px;
}

.block1 {
  position:absolute;
  bottom:0;
  left: 50%;
  height: 100px;
  width: 150px;
  margin-left: -75px;
  background: red;
} 
<div class="parent-block">
  <div class="block1"></div>
</div>

【讨论】:

    【解决方案2】:

    你在正确的轨道上。只需将此 div 上的 leftright 设置为 0,如下所示:

    .block1 {
      position:absolute;
      bottom:0;
      left:0;
      right:0;
      height: 336px;
      width: 1020px;
      margin-left: auto;
      margin-right: auto;
    } 
    

    【讨论】:

      【解决方案3】:

      经典方式:

      .block1 {
        position: absolute;
        bottom: 0;
        height: 336px;
        width: 500px;
        left: 50%;
        transform: translateX(-50%);
        background: purple;
      } 
      &lt;div class="block1"&gt;&lt;div&gt;

      【讨论】:

        猜你喜欢
        • 2016-07-23
        • 2017-07-16
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 2017-06-23
        • 2012-01-20
        • 2013-05-02
        • 2016-08-25
        相关资源
        最近更新 更多