sharataka
sharataka

Reputation: 5132

How to cover the background with an image regardless of size of the background and image?

I am trying to get a background image to cover the entire window but am having trouble getting it to behave the way I'd want.

I currently have

'background-size': 'cover'

However, I find when shrink the width, the image tiles.

enter image description here

So I changed it to:

'background-size': 'cover',
'background-repeat': 'no-repeat'

But now, just white space appears below the image.

enter image description here

So then I tried

'background-size': 'fill',
'background-repeat': 'no-repeat'

However, now when the image is smaller than the window, it doesn't expand to fill the window.

What is the best solution so that the image covers the entire screen, doesn't tile, and doesn't have white space regarldess of the size of the image?

Upvotes: 1

Views: 210

Answers (3)

Rion Williams
Rion Williams

Reputation: 76607

You could explicitly set the size of the background to cover the entire viewport by setting the height to 100vh (i.e. 100% of the available viewport height). This coupled with background-size: cover should handle your scenario :

body {
    background: url('{background-url}');
    background-size: cover;
    height: 100vh;
}

Example

You can see an example of this in action here and demonstrated below :

enter image description here

Upvotes: 3

CodeWeis
CodeWeis

Reputation: 856

you have to give him

height: 100vh

body{margin: 0px;}
div{
  background-image: url(https://placekitten.com/400/600);
  background-size: cover;
  background-position: center;
  height: 100vh;
  width:100%;
}
<div>
  
</div>

Upvotes: 2

LimeFire
LimeFire

Reputation: 11

Try this:

html {
  background: url(...) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Should work with Safari 3+, Chrome Whatever+, IE 9+, Opera 10+, Firefox 3.6+

Source: css-tricks.com

Upvotes: 1

Related Questions