Html css - 如何拉伸和自动调整背景图像的大小

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

css - how to stretch and auto-resize background image

htmlcss

提问by user1283674

I'm trying to get my background image to stretch across the entire page, but so far i have this:

我试图让我的背景图片横跨整个页面,但到目前为止我有这个:

enter image description here

在此处输入图片说明

This is the picture i want stretched across the browser window:

这是我想在浏览器窗口中拉伸的图片:

enter image description here

在此处输入图片说明

My external CSS contains the code below:

我的外部 CSS 包含以下代码:

hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("mybackground.jpg")} 

Can anyone tell me how I can edit the CSS file to fix my problem?

谁能告诉我如何编辑 CSS 文件来解决我的问题?

回答by MMM

You can use:

您可以使用:

background-size: cover;

However please bear in mind which browsers this supports. For example, this won't work in IE8 and below.

但是请记住这支持哪些浏览器。例如,这在 IE8 及更低版本中不起作用。

回答by Arthur Weborg

Another option would also include:

另一种选择还包括:

body{
   background-image:url("mybackground.jpg")
   background-size:contain;
   background-repeat:no-repeat;
}

回答by moodyjive

Background size will do the trick:

背景大小可以解决问题:

    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;
   }

Check this out for more info: http://css-tricks.com/perfect-full-page-background-image/

查看更多信息:http: //css-tricks.com/perfect-full-page-background-image/

回答by alex

Use background-size: cover. Note its browser support.

使用background-size: cover. 注意它的浏览器支持。

MDN documentation.

MDN 文档

回答by digitalextremist

You need to make this an <img>tag, with a low z-index, with position: fixedand then for the <img>tag, use height: 100%; width: autoor the opposite.

你需要把它变成一个<img>标签,用一个 low z-index, withposition: fixed然后为这个<img>标签, useheight: 100%; width: auto或相反。

This method is cross-compatible for all browsers.

这种方法对所有浏览器都是交叉兼容的。

回答by JMG

Have you tried using

你有没有试过使用

background-size: 10px 10px

Change 10 to the width and height of the body

将10改为body的宽高

You can also do

你也可以这样做

background-size: 100%