在 HTML 中,元素是 在流程中 或 在流程之外。
float: right
可用于将元素从流程中取出。
流入和流出元素可以组合,即某些元素可以流入,而其他元素流出在它们旁边。
Flexbox(尤其是
flex: auto
)可用于自动调整in-flow元素的大小。
但是使用弹性盒稍微调整in-flow元素会完全破坏out-of-flow元素:
float: right
元素停止向右浮动,并停止跨越几行:
.container {
display: flex;
flex-wrap: wrap;
align-items: stretch;
}
.container span {
flex: auto;
background-color: gray;
}
.container .float {
float: right;
background-color: yellow;
}
* {
border: 1px solid black;
margin: 1px;
padding: 1px;
}
<div class="container">flexbox
<span class="float">multiline<br>float</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
<span>element with much content</span>
</div>
如何实现某些元素自动调整大小(就像使用
flex: auto
一样)而其他大元素浮动并跨越几行的布局?理想情况下,它不应该太老套(例如在<canvas>
上绘画)。
我想知道是否有更好的解决方案,但这是我当前的解决方案:
可以通过使用
text-align: justify
而不是 Flexbox 来实现该布局。
为了使灰色
<span>
元素之间的白色间隙在所有行中具有相同的宽度,我使用技巧来避免由text-align: justify
引起的扩展。
(在这个技巧之前,我曾尝试将
justify-self: stretch
添加到子元素中,但如果父元素 <div>
有 display: block
则没有效果。我又尝试了父元素 display
的所有可能的 <div>
值,但都没有达到预期的结果。)
.container {
text-align: justify;
}
.container span {
white-space: nowrap;
background-color: gray;
}
.container .float {
float: right;
background-color: yellow;
}
* {
border: 1px solid black;
margin: 1px;
padding: 1px;
}
<div class="container">justified div
<span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span class="float">multiline<br>float</span><span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>no line breaks</span> <span>no line breaks</span> <span>no line breaks</span> <span>no line breaks</span> <span>no line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span> <span>span with suppressed line breaks</span>
</div>
user-select: none
可以阻止选择  
字符,但是这些字符应该用 <span>
包裹在自己的 user-select: none
中(可以更方便地设置其宽度),因为似乎将 user-select: none
设置为父级不能被其他子级覆盖。