html - 为 div 添加边框时出现奇怪的位置问题

标签 html css border css-position margin

html:

    <div class="outside">
         <div class="inside">
         </div>
    </div>

我有两个 CSS:#1 和 #2

 /*CSS#1 does not work*/
.outside{
    background: blue;
    width: 400px;
    height: 400px;
}
.inside{
    background: red;
    width: 200px;
    height: 200px;
    position: relative;
    top: 50%;
    margin: 0 auto;
    margin-top: -100px; /*half height of this div*/
}

/*CSS#2 works well */
.outside{
    border: 1px solid black;
    width: 400px;
    height: 400px;
}
.inside{
    background: red;
    width: 200px;
    height: 200px;
    position: relative;
    top: 50%;
    margin: 0 auto;
    margin-top: -100px; /*half height of this div*/
}

我的目标是将“内部”div 放置在“外部”div 的中心(垂直和水平)。我有很多方法可以实现这个目标,但是在这个过程中我发现了一些奇怪的事情。

我发现 CSS#2 工作得很好,但 CSS#1 不工作:当设置 'inside' div 'margin-top: -100px' 时,'outside' 也向上移动..

这是 demo

所以我想知道为什么“边框”在这里效果很好,为什么“背景”不起作用?

最佳答案

您需要添加 overflow: auto;到那里的父元素,但是你的方法是不正确的,你需要 position 你的子元素 absolute 到父元素而不是 relative/p>

Demo


使用 overflow: auto;border 将解决您的问题,因为它会阻止 collapsing边距

关于html - 为 div 添加边框时出现奇怪的位置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626211/

相关文章:

border - 如何使用 css3 创建圆 Angular 箭头框?

swift - 我在 SwiftUI 的文本字段上使用拐角半径和边框时遇到问题

jquery - jQuery.get() 超时

html - 是否有用于溢出的 css 伪选择器?

javascript - 无法将类添加到元素子项

html - 对齐不同长度的表单输入元素

css - 如何从列表中的最后一项中删除样式?

Python/QT - 我该怎么做才能在一系列小部件之间获得 4 个像素边框?

javascript - 是否可以合并javascript文件以避免过多的http请求

php - 如何创建没有相应页面的重力表单