Html 如何避免内联元素中的换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1426168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:51:46  来源:igfitidea点击:

How can i avoid line break in an inline element?

htmlcss

提问by Martin

I am building a menu with horizontal main entries. Below each the corresponding submenu titles are displayed vertically. Now, some longer menu titles are wrapped over several lines. Actually, the "sub" UL is just as wide as the longest single word in a submenu and all others are wrapped accordingly. I have given no width for the UL nor the LI (neither main nor sub menu).

我正在构建一个带有水平主条目的菜单。在每个相应的子菜单标题下方垂直显示。现在,一些较长的菜单标题包含在几行中。实际上,“子”UL 与子菜单中最长的单个单词一样宽,所有其他单词都相应地包装起来。我没有给出 UL 和 LI 的宽度(既没有主菜单也没有子菜单)。

So my question is, how can I avoid breaking lines? Probably I could substitute each space with  (no-space character), but is there a different way to achieve this?

所以我的问题是,我怎样才能避免断线?可能我可以用 (无空格字符)替换每个空格,但是有没有不同的方法来实现这一点?

回答by Eifion

Have you tried styling the li with

你有没有试过用

white-space: nowrap

?

?

回答by Wayne Austin

adding the following CSS will prevent the line from breaking:

添加以下 CSS 将防止该行中断:

li {
   white-space: nowrap;
}

回答by M K

There is a utility css class text-nowrap. You can find it in the utilitysection of the docs.

有一个实用的 css 类text-nowrap。您可以在文档实用程序部分找到它。

<div style="width: 10px">
    <span class="text-nowrap">This line will not break, ever....!!!</span>
</div>

回答by Tom Harris

Further to M K's answer, the bootstrap utility class text-nowrapapplies white-space: nowraparound it which will mean that any text inside of this class will not break onto a new line. This can be useful but can also be painful when designing responsive code.

继MK的回答,引导实用类text-nowrap应用white-space: nowrap在其周围,这将意味着这一类的任何文本内不会破坏到一个新的生产线。这可能很有用,但在设计响应式代码时也可能很痛苦。

If you have a piece of text that you would like to not break, it's best practice to wrap it around this instead of the parent element:

如果您不想破坏一段文本,最好的做法是将其环绕在此而不是父元素上:

<div class="container">
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in odio
        <span class="text-nowrap">lobortis,</span>
        condimentum ipsum in, vulputate felis. 
    </p>
</div>