繁体   English   中英

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

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

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

这是我的代码:

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

在上面的代码中,ID为"main_wrapper"的DIV我要使用的图像填充屏幕的100%,而ID为"main_content"的DIV我想要一个纯色,居中,宽度仅为1200px。

这是我的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;
}

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

您需要将background-size:cover添加到#main_wrapper 那应该做您想要的。

尝试以下图像尺寸:

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

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

#main_wrapper应该大于#main_content并尝试不使用固定大小

您可以使用更有效的em%auto和其他。

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

 margin: auto;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM