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
How do I add a background image on my DIV tag with CSS
提问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:cover
to #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_wrapper
should be bigger than #main_content
and try to not use fixed size.
#main_wrapper
应该大于#main_content
并尽量不使用固定大小。
you can use more effective em
, %
, auto
and others..
你可以使用更有效em
,%
,auto
等..
回答by Edward
In your #main_content, add the following:
在您的 #main_content 中,添加以下内容:
margin: auto;