Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

html - CSS flex box last space removed

By setting the display of an item to flex I am finding the last space is removed from a text string so.

<div class="has_flex"> Some text <a href="link">Link</a></div>

Becomes

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reason

When you don't use display: flex, the your layout becomes something like

<div class="has_flex"><!--
  --><anonymous style="display: inline">Some text </anonymous><!--
  --><a         style="display: inline">Link</a><!--
--></div>

The text (including the space at the end) is wrapped inside an 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.

However, Flexbox layout blockifies the flex items:

The display value of a flex item is blockified: if the specified display of an in-flow child of an element generating a flex container is an inline-level value, it computes to its block-level equivalent.

Then, the layout will be like

<div class="has_flex"><!--
  --><anonymous style="display: block">Some text </anonymous><!--
  --><a         style="display: block">Link</a><!--
--></div>

This might not seem directly related, but it's relevant because of the white-space processing model:

Then, the block container's inlines are laid out. [...] As each line is laid out, [...]

  1. If a space (U+0020) at the end of a line has white-space set to normal, nowrap, or pre-line, it is also removed.

So when the anonymous element and the link were both inline, the space was at the middle of a line. If you had multiple spaces they would collapse into a single one, but not disappear completely.

However, when you use flexbox, each flex item has its own lines, and the space is therefore at the end of a line. So it's removed.

Note this problem is not specific of flexbox, spaces at the end of an inline-block are also removed.

.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...