如何使用CSS向上移动内框并保持外框在适当位置?

如何使用CSS向上移动内框并保持外框在适当位置?,css,Css,我有以下代码: <html> <head> <style> #yellow {height:100px; background:yellow;} #blue {background:blue;} #red {background:red; width: 400px; height: 100px; margin:0px auto;} </style> </head> <body> <div id="yel

我有以下代码:

<html>
<head>
<style>
#yellow {height:100px; background:yellow;}
#blue {background:blue;}
#red {background:red; width: 400px; height: 100px; margin:0px auto;}
</style>
</head>
<body>
        <div id="yellow"></div>
        <div id="blue">
                <div id="red">Lots of content goes in here that will expand the outer blue box as well</div>
        </div>
</body>
</html>

#黄色{高度:100px;背景:黄色;}
#蓝色{背景:蓝色;}
#红色{背景:红色;宽度:400px;高度:100px;边距:0px自动;}
这里有很多内容,也会扩展外部的蓝色框
我希望红色框向上移动大约30个像素,使其与黄色框和蓝色框重叠。当我试着做一个
#red{margin:-30px auto 0px auto;}
时,蓝色框也随着红色框向上移动了30个像素,尽管我希望蓝色框保持不变

如何使红色框向上移动并重叠黄色和蓝色?

给你

#yellow {
    height:100px;
    background:yellow;
}
#blue {
    background:blue;
}
#red {
    background:red;
    width: 100px;
    height: 100px;
    margin:0px auto;
    position:relative;
    top:-30px;
}
给你

#yellow {
    height:100px;
    background:yellow;
}
#blue {
    background:blue;
}
#red {
    background:red;
    width: 100px;
    height: 100px;
    margin:0px auto;
    position:relative;
    top:-30px;
}

您可以尝试使用
position:relative

#red {
    position: relative;
    top: -30px;
    /* other CSS */
}

您可以尝试使用
position:relative

#red {
    position: relative;
    top: -30px;
    /* other CSS */
}
工作示例:

此示例只需要相对定位,但相对定位和绝对定位可能对您有用

工作示例:

此示例只需要相对定位,但相对定位和绝对定位可能对您有用


在您的案例中,蓝色框包含红色框。因此,您必须相对定位红色框

因此,您只需将以下CSS代码添加到
#red
id

#red { position: relative; top: -30px; }
这是符合您预期结果的代码

<html>
<head>
<style>
#yellow {height:100px; background:yellow;}
#blue {background:blue;}
#red {background:red; width: 400px; height: 100px; margin:0px auto; position: relative; top: -30px;}
</style>
</head>
<body>
        <div id="yellow"></div>
        <div id="blue">
                <div id="red">Lots of content goes in here that will expand the outer blue box as well</div>
        </div>
</body>
</html>

#黄色{高度:100px;背景:黄色;}
#蓝色{背景:蓝色;}
#红色{背景:红色;宽度:400px;高度:100px;边距:0px自动;位置:相对;顶部:-30px;}
这里有很多内容,也会扩展外部的蓝色框

在您的案例中,蓝色框包含红色框。因此,您必须相对定位红色框

因此,您只需将以下CSS代码添加到
#red
id

#red { position: relative; top: -30px; }
这是符合您预期结果的代码

<html>
<head>
<style>
#yellow {height:100px; background:yellow;}
#blue {background:blue;}
#red {background:red; width: 400px; height: 100px; margin:0px auto; position: relative; top: -30px;}
</style>
</head>
<body>
        <div id="yellow"></div>
        <div id="blue">
                <div id="red">Lots of content goes in here that will expand the outer blue box as well</div>
        </div>
</body>
</html>

#黄色{高度:100px;背景:黄色;}
#蓝色{背景:蓝色;}
#红色{背景:红色;宽度:400px;高度:100px;边距:0px自动;位置:相对;顶部:-30px;}
这里有很多内容,也会扩展外部的蓝色框

如果不希望在蓝色底部留有空格,请将底部边距:-30px添加到红色。如果不希望在蓝色底部留有空格,请将底部边距:-30px添加到红色。