nsilva
nsilva

Reputation: 5612

CSS - Responsive - Crop left and right part of a background image as you adjust the width of the browser

I have the following code:-

.content {
      width: 100%;
      text-align: center;
      overflow: hidden;
    }
    
    .expert-header {
      position: relative;
      width: 100%;
      height: 565px;
      display: block;
      background-size: cover !important;
      background: url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg);
    }
    <div class="content">
      <div class="expert-header" style="background:url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg)" ;="">
      </div>
    </div>

    

What I want to achieve is:-

When you start shrinking the browser width from 1920px to 1170px it will cut off (crop) the left and right part of the image.

So if the browser width was at 1720px, essentially 100px will be removed from the left side of the image and 100px removed from the right but the image will retain the 565px height.

How can I achieve this?

I have made a JSFIDDLE of the code I have at the moment.

Upvotes: 2

Views: 6657

Answers (3)

Johannes
Johannes

Reputation: 67778

Use these settings for the background:

.expert-header {
  background: url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg)  center center no-repeat;
  background-size: auto 100%;
}

-> i.e. height 100% of parent element, width proportional to height (auto), centered in both directions (where only the horizontal centering is effective) and witout repeating.

Here's a fiddle: https://jsfiddle.net/q3m23Ly8/1/

(I also removed the style attribute from the HTML)

Upvotes: 2

Jainam
Jainam

Reputation: 2660

Try below css for responsive:

Set the div height as per you needed.

.content {
  width: 100%;
  text-align: center;
  overflow: hidden;
}

.expert-header {
  position: relative;
  width: 100%;
  height: 250px /* Set height as per you needed */;
  display: block;
  background-size: 100% auto !important;
  background: url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg);
  background-repeat: no-repeat !important;
}
<div class="content">
  <div class="expert-header" style="background:url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg)" ;="">
  </div>
</div>

Upvotes: 0

Christoph
Christoph

Reputation: 1630

Remove the inline style of the div element because it will overwrite the CSS rules:

background-size: auto 100%;
background: url(http://igoffice.m360.co.uk/wp-content/uploads/2016/08/paul-expert-header.jpg) center;

The important part is the background-size. auto 100% will tell the browser the background should always cover 100% of the height, the width will be calculated automatically.

Upvotes: 1

Related Questions