Bootstrap - 将DIV对齐到顶部、中间和底部

7
我需要在一个容器DIV中放置三个DIV,所有DIV都要水平居中。第一个DIV需要与容器的垂直顶部对齐,第二个DIV需要与垂直中心对齐,第三个DIV需要与垂直底部对齐。这里有一个关于如何垂直定位DIV的答案, 但没有涉及到其他项目。另一个答案, 但是如何添加需要垂直对齐到顶部和底部的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%的宽度。 - Matt Whiteley
容器 DIV(carousel-caption)具有 width: 90%height: 90% - Alex
1个回答

10

对于这个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

希望这能帮到你!


谢谢,@Ted。这段代码是如何工作的?translateY(-50%)translateY(-100%)是做什么用的? - Alex
2
前50%将中间div的顶部放置在容器高度的50%处,然后translateY(-50%)将其向上移动div高度的50%,从而将其直接定位在中间。底部div的顶部将位于容器的最底部,因此translateY(-100%)将其向上移动div高度的100%,使其正好位于底部。非常好的解决方案。 - Matt Whiteley
1
@Alex - 看起来Matt解释得非常好 :) - Ted
我正在使用这个Bootstrap模板。我注意到的一个问题是,当你调整浏览器窗口大小时(特别是iPhone 5屏幕),3个div会改变垂直位置。有什么想法吗? - Alex
1
position: absolute; 属性设置在 .vcenter.vbottom 上,可以解决在小屏幕和大屏幕上出现排版问题的情况。 - Alex
如果我嵌套vbottom类,这似乎不起作用。有人能解释一下为什么这不起作用,以及为什么它实际上给出了与我想要的完全相反的结果吗?我的导航div最终位于其包含div的上方,而不是底部对齐。 [Bootply演示](https://www.bootply.com/NWUBntlKHA) - Bpainter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接