Html 将 Div 向上移动 20px - 但保留边框

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

Move Div up by 20px - But keep the border

htmlcss

提问by Stefan

i have three <div>s and want to move the second one up.

我有三个<div>s,想将第二个向上移动。

Currently i'm doing this with position: relative; top: -20px;- That works pretty well.

目前我正在这样做position: relative; top: -20px;- 效果很好。

Only downside is: There's a gap (of 20px) between the second <div>and the third <div>(which is under the second div).

唯一的缺点是:第二个<div>和第三个<div>(在第二个 div 下)之间有一个间隙(20px )。

So, i want to keep the border around all three divs, so that top: -20pxis not an alternative for the third row.

所以,我想保留所有三个 div 周围的边框,所以这top: -20px不是第三行的替代方案。

I have this illustrated here: http://jsfiddle.net/w2PGF/1/

我在这里说明了这个:http: //jsfiddle.net/w2PGF/1/

My Markup:

我的标记:

<div id="border">
    <div class="firstRow">foo</div>
    <div class="secondRow">bar</div>
    <div class="thirdRow">foobar</div>
</div>?

My CSS:

我的CSS:

#border {
    border: 5px solid #000;
}
.firstRow {
    background-color: cyan;
    border: 3px solid red;
    height: 50px;
}
.secondRow {
    position: relative;
    top: -20px;
    border: 3px solid yellow;
    background-color: grey;
    height: 50px;
}
.thirdRow {
    background-color: blue;
    border: 3px solid blue;
    height: 50px;
}

Thanks in advance. ?

提前致谢。?

采纳答案by Anthony Mills

.secondRow { margin-bottom: -20px }

回答by Bram Vanroy

Remove the position: relativeand instead of top: -20pxyou should add margin-top: -20px

删除position: relativeand 而不是top: -20px你应该添加margin-top: -20px

Like so: fiddle

像这样:小提琴

回答by Anil

You need to remove the top: -20pxand add margin-top: -20pxto .secondRow

您需要删除top: -20px并添加margin-top: -20px.secondRow

So .secondRowwould look like this: .

所以.secondRow看起来像这样:

secondRow {
    margin-top: -20px;
    border: 3px solid yellow;
    background-color: grey;
    height: 50px;
}

Check this JSFiddle: http://jsfiddle.net/w2PGF/6/

检查这个 JSFiddle:http: //jsfiddle.net/w2PGF/6/