【问题标题】:Vertically align two divs within a background image set to cover在设置为覆盖的背景图像中垂直对齐两个 div
【发布时间】:2017-09-27 00:28:37
【问题描述】:

我有一个div,它使用background-image 属性并将background-size 设置为cover。在包含背景图像的<div> 中,我有一个包含文本块的<div> 和一个包含图像的<div>

我试图在背景图像中垂直对齐两个<div>s。

我有代码(如下),可以将<div>s 相对于彼此垂直对齐,但不在背景图像内。我知道我的代码不起作用,因为垂直对齐需要在 bg 类级别发生,但我不知道如何使它工作。

我有以下 HTML

<div class="bg">
  <div class="container">
    <div class="row vertical-align">
      <div class="col-xs-6">
        <h4 class="text-center">Zack Gallinger has an MBA from Rotman School of Management. He also runs The 10 and 3, a Canadian data journalism site.</h4>
      </div>
      <div class="col-xs-6">
      <img src="http://www.lucidwebgrouptest3.com/Images/Zack.jpg" class="img-circle">
      </div>
    </div>
  </div>
</div>

和 CSS

body,
html {
  height: 100%;
}

.bg {
  background-image: 
url("http://www.lucidwebgrouptest3.com/Images/Background.jpg");
  height: 60%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.vertical-align {
  display: flex;
  flex-direction: row;
}

.vertical-align > [class^="col-"],
.vertical-align > [class*=" col-"] {
  display: flex;
  align-items: center;
  justify-content: center; /* Optional, to align inner items 
                          horizontally inside the column */
}

h4 {
  color: white;
}

代码也在CodePen上。

【问题讨论】:

    标签: css flexbox background-image vertical-alignment


    【解决方案1】:

    您需要为containerrow 添加一个高度,以便它们与bg 匹配

    .container {
      height: 100%;
    }
    
    .vertical-align {
      height: 100%;
      display: flex;
      flex-direction: row;
    }
    

    Updated codepen

    【讨论】:

    • 谢谢!非常有帮助,很高兴解决方案很简单。
    猜你喜欢
    • 2015-10-14
    • 2011-12-21
    • 2016-01-14
    • 2012-10-21
    • 2013-03-06
    • 2013-04-14
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多