简体   繁体   English

CSS:将背景图像拉伸到屏幕的 100% 宽度和高度?

[英]CSS: stretching background image to 100% width and height of screen?

I have an image called myImage.jpg.我有一个名为 myImage.jpg 的图像。 This is my CSS:这是我的 CSS:

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

For some reason, when I do this, the width of myImage stretches across the entire screen but the height only stretches until the height of everything else on the page.出于某种原因,当我这样做时, myImage 的宽度会延伸到整个屏幕,但高度只会延伸到页面上其他所有内容的高度。 So if I put a bunch of所以如果我放一堆

<br>

in my html page, then the height will increase.在我的 html 页面中,高度会增加。 If my HTML page consists only of a如果我的 HTML 页面只包含一个

<div id='header'>
    <br>
</div>

then the height of the background image would just be the height of one那么背景图像的高度将只是一个的高度

<br>

How do I make the height of my background image 100% of the screen which the user is using to view the webpage?如何使我的背景图像的高度达到用户用来查看网页的屏幕的 100%?

You need to set the height of html to 100%您需要将html的高度设置为100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/ http://jsfiddle.net/8XUjP/

I would recommend background-size: cover;我会推荐background-size: cover; if you don't want your background to lose its proportions: JS Fiddle如果你不想让你的背景失去它的比例: JS Fiddle

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

Source: http://css-tricks.com/perfect-full-page-background-image/来源: http : //css-tricks.com/perfect-full-page-background-image/

html, body {
    min-height: 100%;
}

Will do the trick.会做的伎俩。

By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows.默认情况下,即使 html 和 body 也只与它们所包含的内容一样大,但绝不会超过窗口的宽度/高度。 This can often lead to quite strange results.这通常会导致非常奇怪的结果。

You might also want to read http://css-tricks.com/perfect-full-page-background-image/您可能还想阅读http://css-tricks.com/perfect-full-page-background-image/

There are some great ways do achieve a very good and scalable full background image.有一些很好的方法可以实现非常好的和可扩展的完整背景图像。

The VH unit can be used to fill the background of the viewport, aka the browser window. VH单元可用于填充视口的背景,也就是浏览器窗口。

(height:100vh;)

html{
    height:100%;
    }
.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 
     height:100vh;     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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