背景大小:cover与背景大小:contain的区别

3
这是我用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

如何让这个绿色背景保持其形状,使文本在此背景上垂直和水平对齐。

这里是链接到演示页面

感谢您的帮助。


使用contain属性移除固定高度,改用百分比以保持比例...但是无论如何,在某些情况下,图像可能太小而无法保持所需的布局。 - DaniP
1个回答

4
问题是由于您的容器有一个固定的高度 - 它需要保持背景图像的纵横比才能正常工作。
使用 padding css ratio hack,您可以使容器保持纵横比,然后相应地定位行。

#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;
}
<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>


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