.title-strip{
background: green;
margin: 0;
}
.title1 {
overflow: hidden;
}
.title2 {
float: right;
}
<div>
<h1 class="title-strip title1">Title1</h1>
<h1 class="title-strip title2">Title2</h1>
</div>
.title-strip {
background: green;
margin: 0;
}
.title1 {
overflow: hidden;
}
.title2 {
float: right;
}
<div>
<h1 class="title-strip title2">Title2</h1>
<h1 class="title-strip title1">Title1</h1>
</div>
如果第一个h1标签有title1类,第二个标签有title2类,那么文字就在不同的行上。但是当类被交换时,文本就会在不同的行上。为什么会这样呢?
我看了一个堆栈溢出的答案,说'BFCs不允许子孙浮动逃脱它们,也不允许兄弟姐妹浮动侵入它们',同一行的文字结果似乎违背了这一点。难道我说的不对吗?
欢迎来到stackoverflow。溢出:隐藏没有区别(请知道这一点)。当你在一个项目上使用float属性时,即使它是块,它也会作为inline-block。在你这里做的例子中,它所在的行(它可以去的行)向右倾斜,仍然是内联块。
我改变了颜色,以便你能看得更清楚。请仔细检查这两个样本,在第一个例子中,首先使用浮动右元素,然后使用块元素,因为它们切换到了里面。但如果先使用块元素,那么它就会从底线开始继续,而不会覆盖一个区域。
一个小注意:浮动如今已经不经常使用了。相反,我建议你选择display-flex或display-grid等结构。它们都比较简单,而且对于响应式外观也比较有用。我希望描述的是我的意思。
.title-strip {
background: green;
margin: 0;
}
.title1 {
/* overflow: hidden; it doesn't make any difference. */
background-color: yellow;
}
.title2 {
float: right;
background-color: red;
}
<div>
<h1 class="title-strip title2">Title2</h1>
<h1 class="title-strip title1">Title1</h1>
</div>
<div style="height: 75px;"></div>
<div>
<h1 class="title-strip title2" style="margin-top: 50px;">Title2</h1>
<h1 class="title-strip title1">Title1</h1>
</div>
<div style="height: 75px;"></div>
<div>
<h1 class="title-strip title1">Title2</h1>
<h1 class="title-strip title2">Title1</h1>
</div>
我看到一个堆栈溢出的答案说'BFCs不允许子孙浮动逃脱它们,也不允许同级浮动侵入它们'。
这是不正确的,当 overflow
应用到浮动元素上,但当浮动元素 在里面 哪儿 overflow
适用于
这里有一个基本的例子可以理解。
.title-strip {
background: green;
margin: 0;
}
.title1 {
background: red;
}
.title2 {
float: right;
}
<div>
<h1 class="title-strip title2">Title2</h1>
</div>
<h1 class="title-strip title1">Title1</h1>
<br>
<div style="overflow:hidden;">
<h1 class="title-strip title2">Title2</h1>
</div>
<h1 class="title-strip title1">Title1</h1>
在第二个案例中,浮动的标题不再在非浮动标题的右边,因为它在一个带有 overflow:hidden
. 它是自己的BFC,所以它没有更多的互动与任何外部。