gpt4 book ai didi

css - 浏览器如何将相邻的div布局到 float 的div

转载 作者:行者123 更新时间:2023-11-28 09:38:11 24 4
gpt4 key购买 nike

最近开始学习css,在学习float的时候遇到了一些问题。

来自 https://developer.mozilla.org/en-US/docs/Web/CSS/float :

The float CSS property specifies that an element should be taken from the normal flow and >placed along the left or right side of its container, where text and inline elements will >wrap around it.

但我只是想知道,如果一个div跟在 float 元素之后呢?所以我写了一个测试,它没有环绕它,它与它重叠,我真的很困惑,因为有人告诉我 float 元素不会从正常的文档流中获取,下一个 div 将与它左对齐如果有足够的空间。

这是 html 和 css,注意右边的 div 不是 float 的,如果它是 float 的,它会表现出我的预期,但这不是我的问题。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Float Layout</title>
<style type="text/css">
#wrap {
background: #00c;
margin: 0 auto;
width: 960px
}

#header {
background: #FF3300;
width: 100%;
}

#mainbody {
background: #0CF;
width: 100%;
overflow: hidden;
}

#footer {
background: #639;
width: 100%;
}

.left {
width: 140px;
height: 200px;
background: #1f0;
float: left;
}

.right {
width: 140px;
height: 500px;
background: green;
}

</style>
</head>
<body>
<div id="wrap">
<div id="header">header</div>
<div id="mainbody">
<div class="left"><h1>Left</h1></div>
<div class="right"><h1>Right</h1></div>
</div>
<div id="footer">footer</div>
</div>
</body>
</html>

我没有足够的声誉来发布图片。输出是右边的div被左边的div重叠,如果我用段落或h1替换右边的div,它会环绕左边div 这是预期的行为。

我只是想知道为什么右边的div被左边的div重叠,这是一个 float 元素?我无法弄清楚浏览器如何处理这个的解释。如果 float 元素取自正常的文档流,它可以解释这种行为,但这是事实。所以我对此一无所知。

最佳答案

无论您从文档中引用了什么:

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

解释这种行为。

The output is that the right div is overlapped by left div

  • <div>是一个 block 元素,所以它不会环绕 float 元素。
  • float 的 div 从 normalflow 中取出,因此与 div.right .

    如果增加 .right 的宽度,这是可见的.

enter image description here

JSFiddle

if I replace the right div with a paragraph or h1, it will wrap around the left div which is the expected behaviour.

没有。 <p><h1>也是 block 元素,就像 <div> ,因此这不是预期的行为。预期的行为是它们的行为应与 div .right 完全相同。 .这正在发生。

这里要注意的关键是,您可能没有直接在 .right 中使用任何文本。 , 所以你认为 <div>不是包装,而是 <p><h1>正在换行,因为您在其中包含换行的文字:

元素本身没有环绕,(你只是认为它是)只有它们里面的文本环绕 float 元素,因为你指定了 width:140px , 文本空间不足 right坐在 float 的 div 旁边,以便它分解到下一行 - 这是预期的行为。

如果你直接在 .right 中添加一些文本,也会发生同样的事情。 div:它会环绕,但这并不意味着元素本身正在环绕:

<block元素被 float 的 div 重叠,只有文本和内联元素环绕它,这是文档中明确提到的

如果你指定足够的宽度,它会在 float 的 div 旁边对齐

enter image description here

JSFiddle

我在这里没有看到任何出乎意料的事情。

旁注:“因为有人告诉我 float 元素不会从正常的文档流中获取”——我不相信有人会看浏览器开发人员的文档

关于css - 浏览器如何将相邻的div布局到 float 的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25468179/

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