Html 如何创建全宽背景元素?

Html 如何创建全宽背景元素?,html,css,Html,Css,我的页面大小是960px。但是,我希望在页面顶部有两个背景(用于标题),它们将使用100% 全宽黑色背景,下面是全宽灰色背景 我实际上检查了堆栈溢出是如何做到的,看起来我做得不错,但它只对单个元素有效。当我尝试使用第二个元素时,它会超过第一个元素 因此,我的问题是,我如何修复它,以便我将有一个全宽黑色背景,并在它下面有一个全宽灰色背景?从您的bg1和bg2 div中删除负底边距。这样做会将下面的元素向上拉 #bg1 { background: #000; width: 100%

我的页面大小是
960px
。但是,我希望在页面顶部有两个背景(用于标题),它们将使用
100%

全宽黑色背景,下面是全宽灰色背景

我实际上检查了
堆栈溢出是如何做到的,看起来我做得不错,但它只对单个元素有效。当我尝试使用第二个元素时,它会超过第一个元素


因此,我的问题是,我如何修复它,以便我将有一个全宽黑色背景,并在它下面有一个全宽灰色背景?

从您的bg1和bg2 div中删除负底边距。这样做会将下面的元素向上拉

#bg1 {
    background: #000;
    width: 100%;
    height: 60px;
    border-bottom: 1px solid lime;
}
#bg2 {
    background: #ccc;
    width: 100%;
    height: 20px;
    border-bottom: 1px solid cyan;
}

如果我理解您试图正确执行的操作,您只需将容器内容(在本例中为导航)拉入跨越页面宽度的灰色背景中(负上边距)

唯一需要应用负上边距的元素是最后一个背景元素,在本例中,它是
#bg2
——您可以将
#bg1
保留为不带负上边距,因为您不想“拉”内容到其中

因此,您将得到如下CSS(使用当前标记):


这里有一个小提琴示例:

是否要将徽标+导航栏置于黑色背景上?像这样:


你删除、编辑和取消删除的
东西是怎么回事…?你也可以“作弊”,只需制作一个
标题
,黑色的,只需在黑色的底部添加一个灰色的边框:
边框底部:20px实心ccc
\bg1
为什么边距底部?他们不会制造麻烦吗?你能发布一张你想要达到的目标的图片吗?每个人都试图通过猜你想做什么来帮助你。
#bg1 {
    background: #000;
    width: 100%;
    height: 60px;
    margin-bottom: -60px;
    border-bottom: 1px solid lime;
}
#bg2 {
    background: #ccc;
    width: 100%;
    height: 20px;
    margin-bottom: -20px;
    border-bottom: 1px solid cyan;
}

#page-header {height: 60px;}
#page{margin:0 auto;width: 360px;} /* 960px */

body {color: #fff}
nav { float: right; }
nav a { color: #fff; }
#bg1 {
    background: #000;
    width: 100%;
    height: 60px;
    border-bottom: 1px solid lime;
}
#bg2 {
    background: #ccc;
    width: 100%;
    height: 20px;
    border-bottom: 1px solid cyan;
}
#bg1 {
    background: #000;
    width: 100%;
    height: 20px;
    border-bottom: 1px solid lime;
}
#bg2 {
    background: #ccc;
    width: 100%;
    height: 60px;
    margin-bottom: -60px; // This pulls the content below it into this space
    border-bottom: 1px solid cyan;
}
#bg1 {
    background: #000;
    width: 100%;
    height: 60px;
    border-bottom: 1px solid lime;
}
#bg2 {
    background: #ccc;
    width: 100%;
    height: 20px;
    margin-bottom: -20px;
    border-bottom: 1px solid cyan;
}

#page-header {height: 60px;}
#page{margin:-80px auto 0;width: 360px;} /* 960px */

body {color: #fff}
nav { float: right; }
nav a { color: #fff; }