Html 如何使用 CSS 在 DIV 标签上添加背景图像

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

How do I add a background image on my DIV tag with CSS

htmlcssbackgroundbackground-image

提问by user3150191

I'm trying to set my DIV with a background image, but it's not working for me. The image isn't showing up at all. I can't seem to figure out what I'm doing wrong.

我正在尝试使用背景图像设置我的 DIV,但它对我不起作用。图像根本不显示。我似乎无法弄清楚我做错了什么。

Here is my code:

这是我的代码:

<div id="main_wrapper">
        <div id="main_content">
        </div>
</div>

In the above code, the DIV with the id "main_wrapper", i'd like to have the image I'm using fill up 100% of the screen, and the DIV with the id "main_content"I'd like to have a solid color, centered with only 1200px wide.

在上面的代码中,带有 id 的 DIV "main_wrapper",我想让我使用的图像填满屏幕的 100%,带有 id 的 DIV"main_content"我想要纯色,仅居中1200 像素宽。

Here is my CSS:

这是我的 CSS:

#main_wrapper{
    background-image: url('img/bar_bkgnd.png');
    width: 100%;
    height: auto;
    max-width: 1920px;
}

#main_content{
    background-color: #000000;
    height: 800px;
    width: 1200px;
}

If anyone can help me with this issue, that would be very helpful. Thank you for your time!

如果有人可以帮助我解决这个问题,那将非常有帮助。感谢您的时间!

回答by Ben Dyer

You need to add background-size:coverto #main_wrapper. That should do what you're looking for.

您需要添加background-size:cover#main_wrapper. 那应该做你正在寻找的。

回答by T McKeown

try this for the image size:

试试这个图像大小:

#main_wrapper{
 background: url("img/bar_bkgnd.png");
 background-size: 100% 100%;  // or cover like Ben Dyer states
 background-repeat: no-repeat;
}

回答by eapo

Just check the working example: http://jsfiddle.net/8hP4h/

只需检查工作示例:http: //jsfiddle.net/8hP4h/

#main_wrappershould be bigger than #main_contentand try to not use fixed size.

#main_wrapper应该大于#main_content并尽量不使用固定大小

you can use more effective em, %, autoand others..

你可以使用更有效em%auto等..

回答by Edward

In your #main_content, add the following:

在您的 #main_content 中,添加以下内容:

 margin: auto;