Guig
Guig

Reputation: 10187

CSS only full size background image centered with correct ratio

I am looking for a HTML-CSS only solution (no js) to have a background image that would fit its whole container while respecting its ratio and been centered. I'd like the result to be similar to what is achieved here: http://solemone.de/demos/fullsize-background-image-with-css3-background-size/ but without js

The reason why I don't want to use js is because I load the js after everything else and I don't want the user to see an inaccurate background display while loading the page.

Upvotes: 0

Views: 167

Answers (3)

Pain
Pain

Reputation: 185

Here is what I would do. Using CSS3. JSFiddle

CSS3:

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

Works in modern browsers and it scales with the window's size.

Or use CSS only. JSFiddle

HTML:

<img src="http://wallpapersus.com/wp-content/uploads/2012/03/cityscapes-city-night-photography-long-exposure.jpg" class="bg" alt="">

CSS:

img.bg 
{
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: auto;
  position: fixed;
  top: 0;
  left: 0;
}

Its compatible with older and modern browsers.Scales with window's size too.

Note: The way these methods scale the image is to keep the image in nice proportions, in order to look better!

Upvotes: 1

CnapoB
CnapoB

Reputation: 675

Try this

body
{
    background:url(image.png) no-repeat 50% 50%;
    background-size:cover;
}

50% - center background by left, second 50% - center background by top

contain - fit image by object width and height, cover - fit image fully by object w/h.

Upvotes: 0

Robert Dumitrescu
Robert Dumitrescu

Reputation: 87

You can do this with

background: url("path/image.png") center center no-repeat;

And the size of the background with:

background-size: 200px 200px;

Background size supports pixel parameter and % parameter.

Regards!

Upvotes: 0

Related Questions