Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full height Background Image with centered width

I have an 4:3 aspect ratio image to put as a background-image.
My first aim is to have a full height image, resizing accordingly to the height, with variable width (depending on the height). The image should be centered.
For example, if I have a 16:9 viewport it should display the background-image centered with left and right blank spaces.

I tried different method (using as example 4:3 image with 16:9 viewport).
First of all, background-size both with contain and with cover applied to the <body> tag:

  • with cover it respects the aspect ratio but crop the image at the top and at the bottom
  • with contain it doesn't cover the whole viewport, but actually only the body

Also using background-size: auto 100%; produce the same effect as contain

This is the CSS code I used:

 body#home {
  background-image: url(../bg.jpg);
  background-size: auto 100%;
  -moz-background-size: auto 100%;
  -webkit-background-size: auto 100%;
  -o-background-size: auto 100%;
  background-position: center;
  background-repeat: no-repeat;
 }
like image 788
Kropot Avatar asked May 21 '26 15:05

Kropot


1 Answers

Thanks to @Pete, with this code it actually works:

html, body {
  min-height: 100%;
}
body#home {
  background-image: url(../ppersia-home.jpg);
  background-size: contain;
  -moz-background-size: contain;
  -webkit-background-size: contain;
  -o-background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
 }

Now I've just to add some other background pattern to avoid monochrome color in the left and right blank spaces

like image 188
Kropot Avatar answered May 23 '26 07:05

Kropot