Timothy Dodd
Timothy Dodd

Reputation: 11

How to set the size of a background image according to the size of the containing div?

I want to have an image fill a div but not overflow and also be 50% off screen like in this bootply. I have it displaying the way I want it to in the bootply but I was hoping there is a more dynamic way to do this with less code.

Bootply

Upvotes: 0

Views: 44

Answers (2)

Timothy Dodd
Timothy Dodd

Reputation: 11

I figured it out. all I needed was

background-position: top right; background-size: contain;

instead of all of the other code I had for the content div, and then I just cropped my image in photoshop so I wouldn't need to change the horizontal position.

Upvotes: 1

samubreizhizel
samubreizhizel

Reputation: 322

I guess the easiest way of doing this is using the CSS3 FlexBox property. See code and fiddle link below :

HTML:

<link rel="stylesheet" type="text/css" href="style.css" /> 

  <div class="container">
        <div class="div2">
           <p>Sed ut perspiciatis unde omnis iste natus error sit <br>
              accusantium doloremque laudantium, <br>
              totam rem aperiam, eaque ipsa quae
            </p>
      </div>
    <div class="inner-container">
      <ul>
                 <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
              <li>List Item</li>
      </ul>
      <div class="img-container">

      </div>
    </div>
      <div class="div2">
         <p>Sed ut perspiciatis unde omnis iste natus error sit <br>
        accusantium doloremque laudantium, <br>
        totam rem aperiam, eaque ipsa quae</p>
      </div>
    </div>

CSS :

.div2 {background: #777;}

.container{
  display:flex;
  flex-direction:column;
}

.inner-container{
  display:flex;
}

ul{
    min-width:50%;
}

.img-container{
    width: 50%;
    background-image: url('http://image.shutterstock.com/z/stock-photo-lion-head-this-animal-is-considered-to-be-the-king-of-animals-and-white-albino-lion-is-endangered-74806333.jpg');
    background-size:cover;
}

And here is the Fiddle link :

https://jsfiddle.net/smlrolland/rqu2a0g0/4/

Upvotes: 0

Related Questions