<div class="has_flex"> Some text <a href="link">Link</a></div>
变
<div class="has_flex"> Some text<a href="link">Link</a></div>
.has_flex { display: flex; }
<div class="no__flex">Some text <a href="link">Link</a></div> <div class="has_flex">Some text <a href="link">Link</a></div>
我已经将文本包裹在一个范围内,这没有任何区别.
解决方法
当你不使用display:flex时,你的布局变得像
<div class="has_flex"><!-- --><anonymous style="display: inline">Some text </anonymous><!-- --><a style="display: inline">Link</a><!-- --></div>
文本(包括末尾的空格)包含在anonymous inline box中:
Any text that is directly contained inside a block container element (not inside an inline element) must be treated as an anonymous inline element.
但是,FlexBox布局会阻止flex items:
The 07002 value of a 07003 is 07004: if
the specified 07002 of an in-flow child of an element
generating a 07006 is an inline-level value,it computes
to its block-level equivalent.
然后,布局就像
<div class="has_flex"><!-- --><anonymous style="display: block">Some text </anonymous><!-- --><a style="display: block">Link</a><!-- --></div>
这看起来似乎没有直接关系,但是因为the white-space
processing model它是相关的:
Then,the block container’s inlines are laid out. […] As each line
is laid out,[…]
- If a space (U+0020) at the end of a line has
white-space
set tonormal
,nowrap
,orpre-line
,it is also removed.
因此,当匿名元素和链接都是内联时,空间位于一行的中间.如果你有多个空格,它们会崩溃成一个空格,但不会完全消失.
但是,当您使用flexBox时,每个flex项都有自己的行,因此空间位于一行的末尾.所以它被删除了.
请注意,此问题并非特定于flexBox,也会删除内联块末尾的空格.
.in-blo { display: inline-block; }
<div><span class="inline">Some text </span><a href="link">Link</a></div> <div><span class="in-blo">Some text </span><a href="link">Link</a></div>
但是,在这种情况下,您可以将空间移动到内联块之外.在flexBox中,这是不可能的,因为不会呈现仅包含空格的匿名弹性项目.
解
如果要保留空间,可以将空格设置为其他值. white-space:预包装将允许文本换行,白色空间:pre不会.
.has_flex { display: flex; white-space: pre-wrap; }
<div class="no__flex">Some text <a href="link">Link</a></div> <div class="has_flex">Some text <a href="link">Link</a></div>