Html 如何在固定宽度范围内换行或断开长文本/单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18225302/
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
How can I wrap or break long text/word in a fixed width span?
提问by ???? ?????
I want to create a span with a fixed width that when I type any thing in the span like <span>lgasdfjksdajgdsglkgsadfasdfadfasdfadsfasdfasddkgjk</span>
, a long string of non-spaced text, the word(s) break or wrap to next line.
我想创建一个具有固定宽度的跨度,当我在跨度中键入任何内容时,例如<span>lgasdfjksdajgdsglkgsadfasdfadfasdfadsfasdfasddkgjk</span>
一长串非空格文本,单词会中断或换行到下一行。
Any ideas?
有任何想法吗?
回答by Maxime Lorant
You can use the CSS property word-wrap:break-word;
, which will break words if they are too long for your span width.
您可以使用 CSS 属性word-wrap:break-word;
,如果它们对于您的跨度宽度来说太长,则会破坏单词。
span {
display:block;
width:150px;
word-wrap:break-word;
}
<span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>
回答by Gerard de Visser
Try following css with addition of white-space
:
尝试以下 css 添加white-space
:
span {
display: block;
word-wrap:break-word;
width: 50px;
white-space: normal
}
回答by Falguni Panchal
By default a span
is an inline
element... so that's not the default behavior.
默认情况下 aspan
是一个inline
元素......所以这不是默认行为。
You can make the span
behave that way by adding display: block;
to your CSS.
您可以span
通过添加display: block;
到您的 CSS来使行为如此。
span {
display: block;
width: 100px;
}
回答by Eswara Reddy
Try this
尝试这个
span {
display: block;
width: 150px;
}
回答by leopold
Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.
只是为了扩展问题的实际范围并作为给定答案的附录:有时人们可能会发现有必要更多地指定选择器。
By defining the the full span as display:inline-blockyou might have a hard time displaying images.
通过将整个跨度定义为display:inline-block,您可能很难显示图像。
Therefore I prefer to define a span like so:
因此,我更喜欢这样定义跨度:
span {
display:block;
width:150px;
word-wrap:break-word;
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
display:inline-block;
}
img{
display:block;
}
回答by sh6210
In my case, display: block was breaking the design as intended.
就我而言, display: block 按预期破坏了设计。
The max-width
property just saved me.
该max-width
物业只是救了我。
and for styling, you can use text-overflow: ellipsis
as well.
对于样式,您也可以使用text-overflow: ellipsis
。
my code was
我的代码是
max-width: 255px
overflow:hidden