背景大小:封面与背景大小:包含

时间:2016-12-01 14:00:55

标签: css twitter-bootstrap background-image

这是我需要用HTML / CSS实现的,无论屏幕尺寸如何,文本都应始终位于绿色容器内。

enter image description here

这是我的HTML:

<section id="aboutprocess">
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <p class="text-center">Our agile team continuously delivers working software and empowers your organization to embrace changing requirements.
                    </p>
                    <button type="button" class="btn btn-link center-block white" role="link" type="submit" name="op" value="Link 2">about our process</button>
                </div>
                <!--end col-md-8 col-md-offset-2-->
            </div>
            <!--end row -->
        </div>
        <!--end container-->
    </section>
    <!--end aboutprocess-->

为了实现这一观点,我使用了background-size: contain + flexbox

#aboutprocess {
        background: url("../img/tech_bg.png") no-repeat left top;
        width: 100%;
        height: 588px;
        background-size: contain;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
    }

    #aboutprocess p {
        color: #ffffff;
    }

当我调整窗口大小时,文本会出现在外面:

enter image description here

当我使用background-size cover时,绿色背景图片不再显示原始形状:

enter image description here

我怎样才能使这个绿色背景保持其形状并且文本在此背景上保持垂直和水平对齐。

以下是链接to the demo page

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

问题是因为您的容器有一个固定的高度 - 它需要保持背景图像的纵横比才能正常工作

使用padding css ratio hack,您可以让容器保持纵横比,然后相应地定位行:

&#13;
&#13;
#aboutprocess {
  background: url("http://dolm.ragne.me/img/tech_bg.png") no-repeat left top;
  width: 100%;
  background-size: cover;
}
#aboutprocess .container {
  padding-top:  32.6316%;
  position:relative;
}
#aboutprocess .row {
  position:absolute; 
  top:0;
  left:0;
  right:0;
  bottom:0; 
  display:flex;
  align-items: center;
  justify-content:center;
}
#aboutprocess .col-md-8 {
  color: #ffffff;
  text-align:center;
}
&#13;
<section id="aboutprocess">
  <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <p class="text-center">Our agile team continuously delivers working software and empowers your organization to embrace changing requirements.
        </p>
        <button type="button" class="btn btn-link center-block white" role="link" type="submit" name="op" value="Link 2">about our process</button>
      </div>
      <!--end col-md-8 col-md-offset-2-->
    </div>
    <!--end row -->
  </div>
  <!--end container-->
</section>
&#13;
&#13;
&#13;