Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to implement background image on HTML or body

Tags:

html

css

I have an image which i need to stretch whole body so i don't know what is best way to do this

html{
  /*background image properties*/
}

or

body{
  /*background image properties*/
}
like image 678
Srackoveryflow_guy Avatar asked Jan 14 '15 08:01

Srackoveryflow_guy


2 Answers

body{
    background-image:url('../images/background.jpg');
    background-attachment:fixed;
    background-repeat: no-repeat;
    background-size: cover;
}

This would be the best way, you could apply it to the HTML, it really depends on what you prefer...

background-image:url('../images/background.jpg');

Assuming your css file is in a different map, you do ../ to go to the map in which your css folder is placed, then you go into the images file and select the image.

background-attachment:fixed;

When setting a background-image I personally like to use this, it makes it so that when a user scrolls, the background-image maintains it's current position.

background-repeat: no-repeat;

When using this setting, it makes it so that the image won't repeat, in case it is too small or just won't cover the whole background.

background-size: cover;

When you apply this you will set the background-size to cover, combined with no-repeat and attachment: fixed it makes for a good way to style your background image

like image 198
Gerwin Avatar answered Sep 23 '22 23:09

Gerwin


As per the CSS 2.1 Specs here: http://www.w3.org/TR/CSS2/colors.html#background

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element....

Hence, it is recommended to use a background on body (rather than on html).

If you want a background-image to stretch the whole container (i.e. body), then you could use the style:

background-size: 100% 100%;

If you want to preserve the aspect ratio, then you could use cover to make it cover the full container, or use contain to keep it within the container boundary. When you use contain, then depending on the aspect ratio of the background image, you could end up with white-space below or after the image ends (letterbox).

background-image: url('...');
background-size: cover;
background-repeat: no-repeat;
...

.

like image 27
Abhitalks Avatar answered Sep 21 '22 23:09

Abhitalks