简体   繁体   中英

How should the html `height` and the `body's` `background-image` be handled?

I don't know how to better summarize the question, but here's the problem. I set my html's height to 100% as suggested by Kevin Powell and other peoples best practices so things like the footer and such use the whitespace and stick to the bottom of the page, however it presents the problem that if I want to give my body tag a background-image and the current page is "taller" than the viewport the image will start to repeat every 100% of the viewport, ie the 100% set by the html tag, which is not always the desired outcome.

How should I handle this, not to use background-image on my body tag? use a better tiling background-image ?

PS I don't want to resort to having to wrap all my page's content on a wrapper div inside the body tag... unless well it's the only solution. The body tag has min-height of 100% I'm currently on Firefox.

I think it is easily solvable by using

background-size: cover;

source

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

You can also use just the background shorthand to set all the properties at once.

source

https://developer.mozilla.org/en-US/docs/Web/CSS/background

You can set html to occupy 100% of the user's screen by setting min-height: 100vh . then you could set body height to height: 100% to occupy the parent's height (HTML), so this way html and body have the same height if the content is not bigger than 100vh . If you want to have the same background as you scroll in the page, you can set background-attachment: scroll and background-repeat: no-repeat

something like this

html {
  min-height: 100vh;
}

body {
  height: 100%;
  width: 100%;
  background-image: url( /* put your background url here */ );
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: scroll;
}
 

background-attachment doc in MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM