如何用 CSS 在 n 个字符后换行?
How to break after n characters with CSS?
我需要每 20 个字符打破我的 table 单元格。
我发现 CSS 中有一个 ch
单元,它允许我像这样限制我的 max-width
:
td {
max-width: 20ch;
}
这样做会限制我的单元格的宽度,但不会 break/wrap 我的字符串。我尝试申请 word-wrap: break-word
,但这对我也没有帮助。
td {
max-width: 20ch;
word-wrap: break-word; /* does not work */
}
顺便说一下:我的大部分单元格都包含没有空格的字符串。也许这是必要的信息。
编辑
Sorry for late edit, but after some investigation I found out that my <table>
had the css attribute white-space: nowrap;
by my table library. This caused my word-wrap: break-word;
to loose effect.
td {
border-style: solid;
max-width: 20ch;
word-wrap:break-word;
}
<table>
<td>
a;lksjf;dsfasd;lakfjdskl;fadslkfjdsa;lkfdsfa;lkdsjfads;
</td>
</table>
这是你的想法吗?
单元 ch
不是那样工作的。
Represents the width, or more precisely the advance measure, of the glyph "0" (zero, the Unicode character U+0030) in the element's font. Source: mozilla
这意味着它将计算“0”的宽度(基于字体)并将其乘以值(在您的情况下为 20 倍)。这意味着您可以将“0”放入其中 20 次。它不会在任何 20 个字符后中断。仅使用 css
不可能在 20 个字符后断词(只要字符的宽度不同)。你需要一些可编程比如PHP或JavaScript来实现这个。
您可以使用 monospace
字体以相同的宽度呈现所有字符和 word-wrap:break-word
,但是代码段中的 20ch
出于某种原因将导致 16 个字符,所以你需要找到一个允许 20 个字符的设置,在我的设置中(Mac 上的 Firefox)是 24ch
:
td {
font-family: monospace;
border: 1px solid #ddd;
max-width: 24ch;
word-wrap:break-word;
}
<table>
<td>
oiuhncoiuhOOSFwrevi987OINDVouhnweoriuhneaörlvjneriunONVWöoiunoiSAJunwrvwoiunVA
</td>
</table>
我需要每 20 个字符打破我的 table 单元格。
我发现 CSS 中有一个 ch
单元,它允许我像这样限制我的 max-width
:
td {
max-width: 20ch;
}
这样做会限制我的单元格的宽度,但不会 break/wrap 我的字符串。我尝试申请 word-wrap: break-word
,但这对我也没有帮助。
td {
max-width: 20ch;
word-wrap: break-word; /* does not work */
}
顺便说一下:我的大部分单元格都包含没有空格的字符串。也许这是必要的信息。
编辑
Sorry for late edit, but after some investigation I found out that my
<table>
had the css attributewhite-space: nowrap;
by my table library. This caused myword-wrap: break-word;
to loose effect.
td {
border-style: solid;
max-width: 20ch;
word-wrap:break-word;
}
<table>
<td>
a;lksjf;dsfasd;lakfjdskl;fadslkfjdsa;lkfdsfa;lkdsjfads;
</td>
</table>
这是你的想法吗?
单元 ch
不是那样工作的。
Represents the width, or more precisely the advance measure, of the glyph "0" (zero, the Unicode character U+0030) in the element's font. Source: mozilla
这意味着它将计算“0”的宽度(基于字体)并将其乘以值(在您的情况下为 20 倍)。这意味着您可以将“0”放入其中 20 次。它不会在任何 20 个字符后中断。仅使用 css
不可能在 20 个字符后断词(只要字符的宽度不同)。你需要一些可编程比如PHP或JavaScript来实现这个。
您可以使用 monospace
字体以相同的宽度呈现所有字符和 word-wrap:break-word
,但是代码段中的 20ch
出于某种原因将导致 16 个字符,所以你需要找到一个允许 20 个字符的设置,在我的设置中(Mac 上的 Firefox)是 24ch
:
td {
font-family: monospace;
border: 1px solid #ddd;
max-width: 24ch;
word-wrap:break-word;
}
<table>
<td>
oiuhncoiuhOOSFwrevi987OINDVouhnweoriuhneaörlvjneriunONVWöoiunoiSAJunwrvwoiunVA
</td>
</table>