CSS 如何显示全高背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18901819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:27:35  来源:igfitidea点击:

How to show full height background image?

cssimagebackground

提问by hangee

I have a photo type (not landscape) background image with 979px width by 1200px height. I would like to set it to float left and show 100% full image height fixed, without the need to scroll up/down (regardless of content length).

我有一个 979px 宽 x 1200px 高的照片类型(非横向)背景图像。我想将它设置为向左浮动并显示固定的 100% 完整图像高度,而无需向上/向下滚动(无论内容长度如何)。

This is my CSS code, but it is not working:

这是我的 CSS 代码,但它不起作用:

img, media {
    max-width: 100%;
}

body {
    background-color: white;
    background-image: url('../images/bg-image.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

回答by Kevin Lynch

You can do it with the code you have, you just need to ensure that htmland bodyare set to 100% height.

你可以用你拥有的代码来做,你只需要确保htmlbody设置为 100% 高度。

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

演示:http: //jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

回答by Riskbreaker

CSS can do that with background-size: cover;

CSS 可以使用background-size: cover;

But to be more detailed and support more browsers...

但要更详细并支持更多浏览器......

Use aspect ratio like this:

像这样使用纵横比:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

小提琴

回答by him

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}