Luke
Luke

Reputation: 2400

How to scale background-image to fit responsive div

I'm trying to make a "Did you know?" fixed div in the right corner. Unfortunately after 3 hours of testing many solutions still can't find correct one. As you can see on this fiddle: http://jsfiddle.net/dq8f3d4p/ I can't make the background fit the div.

Both: background-size: cover; and background-size: 100%; seems not to work properly.

Upvotes: 0

Views: 4244

Answers (3)

Aditya Shedge
Aditya Shedge

Reputation: 386

put the image inside you div and then fix the div to bottom right

<div class="dyk">
    <img src="http://i.imgur.com/gxp9iDV.png"></img>
</div>

.dyk{
    position: fixed;
    z-index:2;
    right: 0;
    bottom: 0;
}

Upvotes: -1

Yotam Omer
Yotam Omer

Reputation: 15356

You are probably looking for background-size:contain;, Which is usually the best pick, however, in your case the image proportions and the div's proportions are not the the same so I would recommend using background-size: 100% 100%;.

    background: url(http://i.imgur.com/gxp9iDV.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;

Working jsFiddle

Notes:

  1. background-size is supported by IE9+
  2. Use contain if you don't want your image to get streched.

Upvotes: 2

Abhishek Goyal
Abhishek Goyal

Reputation: 877

In your code, you are overwriting background-size with the shorthand background property :

.dyk{
    position: fixed;
    z-index:2;
    width: 17.26%;
    height: 11%;
    left: 80%;
    top: 80%;
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url(http://i.imgur.com/gxp9iDV.png);
}

Changing it to background-image property will cause the image to stretch to 100% size.

Upvotes: 4

Related Questions