在CSS中设置最大字符长度

我正在为学校做响应式网站,我的问题是:

我如何在我的网站上设置句子的最大字符长度(用CSS)(比如75个字符),当我有一个非常大的屏幕时,句子不会超过75个字符。

我已经尝试了最大宽度,但这打乱了我的布局。我使用flexbox和媒体查询,使其响应。

717931 次浏览

这在CSS中是不可能的,你必须使用Javascript。虽然你可以设置p的宽度为30个字符,下一个字母会自动下来,但这不会那么准确,如果字符是大写的,会有所不同。

你总是可以通过设置max-width来使用截断方法,并像这样溢出ellipsis

p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}

一个例子:

.wrapper {
padding: 20px;
background: #eaeaea;
max-width: 400px;
margin: 50px auto;
}


.demo-1 {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}


.demo-2 {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 150px;
}
<div class="wrapper">
<p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>


<div class="wrapper">
<p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>

对于多行截断,请查看flex解决方案。

p {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}

一个例子:

p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!</p>

CSS的“长度值”为ch

From MDN

这个单位代表宽度,或者更准确地说是提前测量, 符号“0”(0,Unicode字符U+0030)在元素的 字体。< / p >

这大概就是你想要的。

p {
overflow: hidden;
max-width: 75ch;
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque.</p>

超文本标记语言

<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>

jQuery

var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
$(p).text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}

CSS

#dash {
width: 400px;
height: 60px;
overflow: hidden;
}


#dash p {
padding: 10px;
margin: 0;
}

结果

< b>我是孤独的,神圣的,神圣的。Proin非绝对的 Ligula, dapibus a volutpat sit amet, mattis et…

Jsfiddle

尝试在设置为max-width后截断字符。在这种情况下我使用了75ch

p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 75ch;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc.</p>

For multiline truncating, please follow the link.

An example: https://codepen.io/srekoble/pen/EgmyxV

We will be using webkit css for this. In short WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. This may be brower specific as every browser is backed by a rendering engine to draw the HTML/CSS web page.

用两种不同的方法试试我的解决方案。

<div class="wrapper">
<p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>


<div class="wrapper">
<p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>


.wrapper {
padding: 20px;
background: #eaeaea;
max-width: 400px;
margin: 50px auto;
}


.demo-1 {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}


.demo-2 {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 150px;
}

示例代码:

.limited-text{
white-space: nowrap;
width: 400px;
overflow: hidden;
text-overflow: ellipsis;
}
<p class="limited-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>


纯CSS解决方案截断多行字符

我有一个类似的问题,并从Hackingui.com找到这个优秀的css唯一解决方案。您可以阅读文章获取信息,但下面是主要代码。

我测试过了,效果很好。希望有人在选择JS或服务器端选项之前发现它有用

  /* styles for '...' */
.block-with-text {
/* hide text if it more than N lines  */
overflow: hidden;
/* for set '...' in absolute position */
position: relative;
/* use this value to count block height */
line-height: 1.2em;
/* max-height = line-height (1.2) * lines max number (3) */
max-height: 3.6em;
/* fix problem when last visible word doesn't adjoin right side  */
text-align: justify;
/* place for '...' */
margin-right: -1em;
padding-right: 1em;
}


/* create the ... */
.block-with-text:before {
/* points in the end */
content: '...';
/* absolute position */
position: absolute;
/* set position to right bottom corner of block */
right: 0;
bottom: 0;
}


/* hide ... if we have text, which is less than or equal to max lines */
.block-with-text:after {
/* points in the end */
content: '';
/* absolute position */
position: absolute;
/* set position to right bottom corner of text */
right: 0;
/* set width and height */
width: 1em;
height: 1em;
margin-top: 0.2em;
/* bg color = bg color under block */
background: white;
}

现代CSS网格答案

查看CodePen上的完整工作代码。给定以下HTML:

<div class="container">
<p>Several paragraphs of text...</p>
</div>

您可以使用CSS Grid创建三个列,并告诉容器将包含段落的中间列的最大宽度设置为70个字符。

.container
{
display: grid;
grid-template-columns: 1fr, 70ch 1fr;
}


p {
grid-column: 2 / 3;
}

它看起来是这样的(签出CodePen以获得一个完整的工作示例):

enter image description here

下面是另一个示例,您可以使用minmax来设置一个值范围。在小屏幕上,宽度将设置为50个字符宽,在大屏幕上,宽度将设置为70个字符宽。

.container
{
display: grid;
grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}


p {
grid-column: 2 / 3;
}

在Chrome浏览器中,你可以设置“-webkit-line-clamp”显示的行数:

     display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;  /* Number of lines displayed before it truncate */
overflow: hidden;

所以对我来说,它是在一个扩展中使用,所以它是完美的,更多信息在这里:https://medium.com/mofed/css-line-clamp-the-good-the-bad-and-the-straight-up-broken-865413f16e5

这篇文章是关于一个CSS解决方案的,但这篇文章已经很老了,所以为了防止其他人偶然发现这一点,并且正在使用一个现代的JS框架,比如Angular 4+,有一个简单的方法可以通过Angular Pipes来实现这一点,而不必在CSS上瞎忙活。

可能也有“React”或“Vue”的方法来做到这一点。这只是为了展示如何在框架中完成它。

truncate-text.pipe.ts

/**
* Helper to truncate text using JS in view only.
*
* This is pretty difficult to do reliably with CSS, especially when there are
* multiple lines.
*
* Example: \{\{ value | truncateText:maxLength }} or \{\{ value | truncateText:45 }}
*
* If maxLength is not provided, the value will be returned without any truncating. If the
* text is shorter than the maxLength, the text will be returned untouched. If the text is greater
* than the maxLength, the text will be returned with 3 characters less than the max length plus
* some ellipsis at the end to indicate truncation.
*
* For example: some really long text I won't bother writing it all ha...
*/
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
transform(value: string, ...args: any[]): any {
const maxLength = args[0]
const maxLengthNotProvided = !maxLength
const isShorterThanMaximumLength = value.length < maxLength
if (maxLengthNotProvided || isShorterThanMaximumLength) {
return value
}
const shortenedString = value.substr(0, maxLength - 3)
return `${shortenedString}...`
}
}

app.component.html

<h1>\{\{ application.name | truncateText:45 }}</h1>

你可以看看你的字体有多宽,然后取平均字符像素大小。然后再乘以你想要的字符数。这有点俗气,但它是一种快速的解决方法。

From mdn

在所有浏览器中完全支持。

75个字符

我已经尝试了最大宽度,但这打乱了我的布局。

使用max-width: 75ch,然后创建一个布局,当你超过这个宽度时不会乱。

这段代码工作:

.on_table{
table-layout: fixed;
}


.on_tr_td{
border:1px solid grey;
max-width: 20ch;
color: green;
word-break:break-all
}