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

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

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


当前回答

示例代码:

.limited-text { 空白:nowrap;} 宽度:400 px; 溢出:隐藏; 文本溢出:省略; } <p class="limited-text">我爱你,我爱你。时间和欲望是错误的,是腐败的,是幸福的!</p> .</p

其他回答

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

纯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;
}

75个字符

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

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

在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网格答案

在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;
}

这是它的样子(Checkout CodePen是一个完整的工作示例):

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

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

p {
  grid-column: 2 / 3;
}