防止文本溢出HTML中的填充容器

时间:2023-02-14 21:07:41

I have this situation:

我有这种情况:

<div style="width: 100px; padding: 5px 15px 5px">Some text longer than 100px</div>

If I set overflow: hidden on the div the text will still go outside the 15px padded area on the right:

如果我设置溢出:隐藏在div上,文本仍然会出现在右边的15px填充区域之外:

++----------------------------+------+
++----------------------------+------+
||This text should stop here -| but i|
++----------------------------+------+
++----------------------------+------+

Can this be done without putting an extra element inside to hold the text. Any solution in any browser will do, I just want to know if it's possible.

可以在不添加额外元素来保存文本的情况下完成此操作。任何浏览器中的任何解决方案都可以,我只是想知道它是否可行。

3 个解决方案

#1


26  

You can use a transparent border to make the margin you want. It won't be overflowed:

您可以使用透明边框来制作所需的边距。它不会溢出:

div {
    white-space: nowrap;
    overflow: hidden;
    max-width: 300px;
    border-left:1em solid transparent;
    border-right:1em solid transparent;
    text-overflow: ellipsis;
}

#2


12  

did you try:

你试过了吗:

word-wrap:break-word;

it automatically breaks word to next line when end is reached.

到达结束时,它会自动将单词分隔到下一行。

#3


-1  

Hey I don't know about your requirement exactly, there is one way to truncate the text using css3 ellipsis property.

嘿我完全不知道您的要求,有一种方法可以使用css3省略号属性截断文本。

Example

a) Normal case

a)正常情况

+-------------------------++
some text which is exceeding the container
+-------------------------++

b) After implementing ellipsis

b)实现省略号后

+-------------------------++
some text which is exceed...
+-------------------------++

Here is the reference link: https://developer.mozilla.org/En/CSS/Text-overflow which have the browser support information also.

以下是参考链接:https://developer.mozilla.org/En/CSS/Text-overflow,其中也包含浏览器支持信息。

Hope this helps!

希望这可以帮助!

#1


26  

You can use a transparent border to make the margin you want. It won't be overflowed:

您可以使用透明边框来制作所需的边距。它不会溢出:

div {
    white-space: nowrap;
    overflow: hidden;
    max-width: 300px;
    border-left:1em solid transparent;
    border-right:1em solid transparent;
    text-overflow: ellipsis;
}

#2


12  

did you try:

你试过了吗:

word-wrap:break-word;

it automatically breaks word to next line when end is reached.

到达结束时,它会自动将单词分隔到下一行。

#3


-1  

Hey I don't know about your requirement exactly, there is one way to truncate the text using css3 ellipsis property.

嘿我完全不知道您的要求,有一种方法可以使用css3省略号属性截断文本。

Example

a) Normal case

a)正常情况

+-------------------------++
some text which is exceeding the container
+-------------------------++

b) After implementing ellipsis

b)实现省略号后

+-------------------------++
some text which is exceed...
+-------------------------++

Here is the reference link: https://developer.mozilla.org/En/CSS/Text-overflow which have the browser support information also.

以下是参考链接:https://developer.mozilla.org/En/CSS/Text-overflow,其中也包含浏览器支持信息。

Hope this helps!

希望这可以帮助!