【问题标题】:Vertically align center and margin using absolute position使用绝对位置垂直对齐中心和边距
【发布时间】:2017-09-27 22:14:18
【问题描述】:

如何使用绝对位置垂直居中对齐 div?如果在单列中找到多个 div,则该 div 应该有 margin-bottom。

.parent { 
    position: relative;
    background: #FF0000;
    width: 100%;
    height: 100px;
    padding:20px 0px;
    }
.children_multiple_in_column { 
    position: absolute;
    background: #000;
    width: 150px;
    height: 20px;
    bottom: 50%;
    top: 50%;
    margin-bottom: 50px;
    color: white;
    z-index=1;
    }
.children_single_in_column { 
    position: absolute;
    background: #000;
    width: 150px;
    height: 20px;
    left: 60%;
    bottom: 50%;
    top: 50%;
    color: white;
    z-index=1;
}

JSFiddle 在这里:http://jsfiddle.net/richersoon/m8kp92yL/8/

结果应该是这样的:

请忽略不重要的水平线。

【问题讨论】:

    标签: html css


    【解决方案1】:

    将多个项目包装在一个 div 中,并使用transform: translateY(-50%); top: 50%; 进行垂直对齐。

    .parent {
      position: relative;
      background: #FF0000;
      width: 100%;
      height: 100px;
      padding: 20px 0px;
    }
    
    .parent>div {
      position: absolute;
      background: #000;
      width: 150px;
      top: 50%;
      color: white;
      transform: translateY(-50%);
      z-index: 1;
    }
    
    .children_single_in_column {
      left: 60%;
    }
    
    .multiple>div {
      margin-bottom: 10px;
    }
    
    .multiple>div:last-child {
      margin-bottom: 0;
    }
    <div class="parent">
      <div class="multiple">
        <div class="children_multiple_in_column">Monday Task 1</div>
        <div class="children_multiple_in_column">Monday Task 2</div>
      </div>
      <div class="children_single_in_column">Friday Task 1</div>
    </div>

    示例:JSfiddle

    【讨论】:

    • 我们可以在不添加另一个 div(“多个”div)的情况下做到这一点吗?
    • 通常不会,除非您不希望它是动态的(根据内容进行更改)。您可以使用 .three-children 或 JS 之类的类,但最简单的方法是包装它。你也可以用 JS 来包装它。
    猜你喜欢
    • 2017-03-23
    • 2013-06-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多