【问题标题】:Bootstrap - Align DIVs to top, middle, and bottomBootstrap - 将 DIV 对齐到顶部、中间和底部
【发布时间】:2015-03-25 14:24:40
【问题描述】:

我需要在一个容器 DIV 中有三个 DIV,全部水平居中。第一个需要与容器的垂直顶部对齐,第二个与垂直中心对齐,第三个与垂直底部对齐。这是an answer 用于垂直定位 div,但不涉及其他项目。另一个答案here,但是如何将需要垂直对齐的DIV添加到顶部和底部?

这是 HTML:

<div class="carousel-caption"> <!-- outer container; all items horizontally centered -->
    <div class="row align-top"> <!-- align this DIV to top -->
        <h1 class="col-sm-12">Top DIV</h1>
    </div>
    <div class="row align-vertical-center"> <!-- align this DIV to center -->
        <div class="col-sm-12 ">Middle DIV</div>
    </div>
    <div class="row align-vertical-bottom">
        <div class="align-vertical-bottom">Bottom DIV</div>
    </div>
</div>

【问题讨论】:

  • 容器div有指定的高度吗?如果它将根据内部 div 变化,那么您只需为每个内部 div 赋予 100% 的宽度。
  • 容器 DIV (carousel-caption) 有 width: 90%height: 90%

标签: html css twitter-bootstrap twitter-bootstrap-3


【解决方案1】:

对于这个 HTML:

<div class="container">
  <div class="carousel-caption"> <!-- outer container; all items horizontally centered -->
    <div class="row vtop"> <!-- align this DIV to top -->
        <div class="col-sm-12">Top DIV</div>
    </div>
    <div class="row vcenter"> <!-- align this DIV to center -->
        <div class="col-sm-12 ">Middle DIV</div>
    </div>
    <div class="row vbottom">
        <div class="col-sm-12 vbottom">Bottom DIV</div>
    </div>
  </div>
</div>

这个 CSS:

.carousel-caption{
    padding:0;
 }

.vtop{
  /*padding on parent fixes this*/
}

.vcenter{
    position: relative;
    top: 50%;
    transform: translateY(-50%); 
}

.vbottom{
    position: relative;
    top: 100%;
    transform: translateY(-100%); 
}

this Bootply Demo

HTH!

【讨论】:

  • 谢谢,@Ted。这段代码是如何工作的? translateY(-50%)translateY(-100%) 有什么作用?
  • 前 50% 将中间 div 的顶部置于容器高度的 50% 处,然后 translateY(-50%) 将其向上移动 div 高度的 50%,因此直接放在中间。底部 div 的顶部将位于容器的最底部,因此 translateY(-100%) 将其向上移动 100% 的 div 高度,因此它正好位于底部。很好的解决方案。
  • @Alex - 看起来马特很好地解释了它。 :)
  • 我在 Bootstrap 模板中使用它。我注意到的一个问题是,当您调整浏览器窗口的大小(尤其是 iPhone 5 屏幕)时,3 个 div 会改变垂直位置。有什么想法吗?
  • 在 .vcenter 和 .vbottom 上设置 position: absolute; 解决了在小屏幕和大屏幕上出现问题的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多