11

I have the following HTML:

<div class="jumbotron">
    <div class="container">
        <h1>Souplesse</h1>
        <p>Be a Good Sport</p>
    </div>
</div>

And the following CSS:

.jumbotron {
  background-image:url('piscine.jpg');
  height:300px;
  background-repeat: no-repeat;
  background-size: cover;
  border-bottom:1px solid #ff6a00
}
.jumbotron .container {
  position:relative;
  top:50px;
}

My image is far too large to fit my height of 300px but I would like it to auto-resize and fit the height, so I can see all of my image. This must be simple but I can't see what changes need to be made.

Thanks

jmn8
  • 623
  • 2
  • 7
  • 15

2 Answers2

33

If you would like the background image to fit the height of your jumbotron, but don't care about if it stretches to the entire width:

.jumbotron { background-size: auto 100%; }

If you want the background image to cover the entire height AND width of the jumbotron and you do not care about the image's aspect ratio:

.jumbotron {background-size: 100% 100%; }

If you want the background image to be cover the entire height AND width the jumbotron but you DO care about the image's aspect ratio:

.jumbotron { background-size: cover; }

That last option will have some of the image cut off if the jumbotron has a different aspect ratio than the image, but you can specify how the image is positioned with the background position property:

.jumbotron {
    /* Image in the center of container */
    background-position: center center;

    /*  OR Image in the center top of the container */
    background-position: center top;

    /*  OR Image in the center bottom of the container  */
    background-position: center bottom;
}
Pete Droll
  • 361
  • 2
  • 5
  • 1
    Cheers Pete - this covers all bases and is some excellent knowledge. Thanks for sharing. – jmn8 Jun 30 '15 at 21:52
  • My challenge with using "cover" is when the client wants the entire image to always be visible at 100% width. Currently I'm working on a page where the image width spans the entire browser, but the bottom of the image gets cut off when viewing on large screens. – user3120861 Nov 11 '20 at 21:09
  • [`background-size: cover;`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#contain) might be a good option for you then. "It scales the image as large as possible within its container without cropping or stretching the image." – Pete Droll Jan 05 '21 at 21:40
0

Try:

.jumbotron {
  background-image:url('piscine.jpg');
  height:300px;
  background-repeat: no-repeat;
  background-size: auto 100%;
  border-bottom:1px solid #ff6a00
}

Note the:

background-size: auto 100%;

The first value is the width, the second value is the height. It is compliant to use px or % for those values.

  • This semi-works however you'll find that when you zoom in and out of the page (at least in Chrome, which I am using) the image will stop fitting. – jmn8 Jun 30 '15 at 21:52