使用 css 或 jquery 将背景图像调整为全高和全宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28559845/
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 02:59:54  来源:igfitidea点击:

background image to full height and width using css or jquery

cssbackground-image

提问by Alaksandar Jesus Gene

I want the background image for my home div only which is visible only for desktops and tablets(landscape). I could adjust them with CSS media query.

我只想要我的家庭 div 的背景图像,它仅对台式机和平板电脑(横向)可见。我可以用 CSS 媒体查询来调整它们。

But my background image is not fitting to full height.

但是我的背景图片不适合全高。

here is my pluner code. http://plnkr.co/edit/HzlZdqvprkhzO1edqNKK?p=preview

这是我的plner代码。http://plnkr.co/edit/HzlZdqvprkhzO1edqNKK?p=preview

my jquery code

我的jQuery代码

$(document).ready(function(){
    console.log($('.home').height());
});

is also returning null.

也返回空值。

What is the best way to solve this.

解决这个问题的最佳方法是什么。

回答by Nick

addi this code to youre image, and you wil l have your result without jquery:

将此代码添加到您的图像中,您将获得没有 jquery 的结果:

background: url(http://www.pulsarwallpapers.com/data/media/3/Alien%20Ink%202560X1600%20Abstract%20Background.jpg) no-repeat center center fixed;
background-size: cover;
height: 400px;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;

the secret is using background-size: cover and then set the background as fixed with height and width 100%

秘诀是使用 background-size: cover 然后将背景设置为固定的高度和宽度 100%

回答by Ajay Narain Mathur

console.log($('.home').height()); is returning null as you have not set height attribute for home div.

console.log($('.home').height()); 返回 null,因为您尚未为 home div 设置高度属性。

set height attribute and then you can use it or do Nick told background-size: auto 100%;

设置高度属性然后你可以使用它或者做 Nick 告诉 background-size: auto 100%;

回答by Rasel

use background-sizeproperty of css

使用 background-sizecss的属性

background-size: 100% 100%;

回答by Nick

http://jsfiddle.net/fynbc5uv/
You said you didn't want to set height, the only workaround for this is setting the background-image on the body. CSS:

http://jsfiddle.net/fynbc5uv/
你说你不想设置高度,唯一的解决方法是在身体上设置背景图像。CSS:

body{height:100%;
   background: url(http://www.pulsarwallpapers.com/data/media/3/Alien%20Ink%202560X1600%20Abstract%20Background.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}