gpt4 book ai didi

html - 带有 float Div 的 Ghost Top Body 边距

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:16 25 4
gpt4 key购买 nike

我编写了以下代码并尝试将三个左浮动的 div 放置在包含 div 的父亲中。出于某种原因,body 标签似乎有一个幽灵顶部边距,这是我的代码中未定义的属性。但是,如果我删除包含 div 的 margin-bottom 属性或对其应用 clearfix 样式,则上边距将消失。是什么原因导致重影顶部边距以及如何解决它?谢谢!

检查下面的屏幕截图:

  • 原代码:

    enter image description here

  • Margin-bottom 移除:

    enter image description here

    • 应用了 Clearfix 样式:

    enter image description here

这是原始代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
html {
font: 16px/2 Tohoma, Verdana, Arial, Sans-serif, 'Microsoft YaHei';
background: #ccc;
}

body {
margin: 0;
padding: 0;
}

.clear-fix:after {
content: '';
display: block;
clear: both;
}

#wrap {
margin: 0 auto;
width: 1000px;
min-height: 800px;
background: #fff;
}

#header {
margin-bottom: 20px;
}

.first, .second, .third {
float: left;
padding: 20px;
min-height: 100px;
}

.first {
background: gray;
}

.second {
background: blue;
}

.third {
background: yellow;
}
</style>
<title>
Another Web Page
</title>
</head>
<body>
<div id="wrap">
<div id="header">
<div class="first">This is the first floating division</div>
<div class="second">This is the second floating division</div>
<div class="third">This is the third floating division</div>
</div>
</div>
</body>
</html>

原始代码预览: http://jsfiddle.net/qv8ph0gw/

最佳答案

解释:

这里发生了一些事情。

当元素绝对定位 float 时(如您的情况),它们将从文档的正常流中移除。以下是证实这一点的相关文件:

9 Visual formatting model - 9.5 Floats

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

在您的例子中,#header 元素的子元素是 float 的。由于 所有 子元素都是 float 的,因此 #header 元素基本上会自行折叠,因为它没有任何维度。

这是一个视觉示例。如您所见,父元素 #header 的高度为 0:

collapsed

由于该元素的高度为 0,因此 margin-bottom 本质上充当 margin-top,而 margin collapses使用 body 元素。

我刚刚回答了关于 collapsing margins here 的问题,但这里是相关文档:

Box Model 8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

可能的解决方案/解决方法:

如您所述,我通过向 #header 元素添加 clearfix 解决了该问题。 clearfix 本质上是防止父元素自行折叠,这意味着底部边距不会折叠。

您可以通过简单地向元素添加 overflow: hidden 来实现完全相同的事情:

Example Here

#header {
margin-bottom: 20px;
overflow: hidden;
}

关于html - 带有 float Div 的 Ghost Top Body 边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com