bijoume bijoume - 9 days ago 4
CSS Question

Background-size: cover versus background-size: contain

This is what I need to achieve with my HTML/CSS, the text should always be inside the green container, no matter what the screen size is.

enter image description here

This is my 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-->


In order to achieve this view, I've used
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;
}


When I resize the window, the text falls outside:

enter image description here

When I use
background-size cover
, the green background image doesn't show the original shape any more:

enter image description here

How could I make it work that this green background remains its shape and text stays on this background aligned both vertically and horizontally.

Here is the link to the demo page.

Thank you for your help.

Answer

The problem is caused as you have a fixed height for your container - it needs to keep the aspect ratio of the background image to work properly

Using the padding css ratio hack, you can get the container to keep the aspect ratio and then position the row accordingly:

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