coder123
coder123

Reputation: 183

CSS background image cover

I am struggling to understand why I am unable to get the background-cover property to work inside of my div?

.box {
  height: 240px;
  width: 31.1111%;
  margin: 0px;
  float: left;
  box-sizing: border-box;
  border: 10px solid #fff;
  margin: 1.11111%;
  -webkit-box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.15);
  -moz-box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.15);
  box-shadow: 0px 0px 5px 0px rgba(50, 50, 50, 0.15);
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<div class="box" style="background:url('http://www.addictedtoibiza.com/wp-content/uploads/2012/12/example.png');">
  <div class="overlay">
    <div class="buttonContainer">
      <button>preview</button>
    </div>
  </div>
</div>

Upvotes: 0

Views: 491

Answers (3)

Aron
Aron

Reputation: 150

This will work if you change background to background-image see working demo here: http://jsfiddle.net/3t7ftpky/

Why does this work?

background is a shorthand property and by putting it inline it overrides the other background-size properties in the stylesheet. you can find out more about the css background property here:

Upvotes: 1

joseluisq
joseluisq

Reputation: 528

background is a general property, so this includes: backgound-image, background-size, background-color, background-position, etc.

So you should to use in this case background-image only, because background is overwriting your above css defined properties.

Regards

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240878

Inline styling has a higher specificity. Therefore background is overwriting the property shorthand background-size.

Change background to background-image:

Updated Example

<div class="box" style="background-image:url('http://www.addictedtoibiza.com/wp-content/uploads/2012/12/example.png');">
    <div class="overlay">
        <div class="buttonContainer">
            <button>preview</button>
        </div>
    </div>
</div>

After looking at the example, it seems like you may be more interested in using the value contain rather than cover. (example)

Upvotes: 3

Related Questions