文本溢出省略号在两行上

时间:2013-04-09 18:17:11

标签: html css

我知道你可以使用CSS规则的组合,当溢出时间(离开父边界)时,文本以省略号(...)结尾。

是否可以(随意说,不)实现相同的效果,但是让文字换行多行?

Here's a demo

div {
  width: 300px; 
  height: 42px; 
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap;
}

正如您所看到的,当文本比div的宽度更宽时,文本以省略号结尾。但是,仍然有足够的空间让文本换行第二行并继续。这被white-space: nowrap中断,这是省略号工作所必需的。

有什么想法吗?

P.S。:没有JS解决方案,如果可能的话,纯CSS。

17 个答案:

答案 0 :(得分:69)

简单的CSS属性可以解决问题。以下是三行省略号。

display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;

答案 1 :(得分:30)

我不确定你是否见过THIS,但是Chris Coyier的优秀CSS-Tricks.com发布了一段时间的链接,这是一个纯粹的CSS解决方案这完全符合你的要求。

(Click to View on CodePen)

HTML:

<div class="ellipsis">
    <div>
        <p>
            Call me Ishmael. Some years ago – never mind how long precisely – having
            little or no money in my purse, and nothing particular to interest me on
            shore, I thought I would sail about a little and see the watery part of the
            world. It is a way I have of driving off the spleen, and regulating the
            circulation. Whenever I find myself growing grim about the mouth; whenever it
            is a damp, drizzly November in my soul; whenever I find myself involuntarily
            pausing before coffin warehouses, and bringing up the rear of every funeral I
            meet; and especially whenever my hypos get such an upper hand of me, that it
            requires a strong moral principle to prevent me from deliberately stepping
            into the street, and methodically knocking people's hats off – then, I account
            it high time to get to sea as soon as I can.
        </p>
    </div>
</div>

CSS:

html,body,p {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
.ellipsis {
    overflow: hidden;
    height: 200px;
    line-height: 25px;
    margin: 20px;
    border: 5px solid #AAA;
}
.ellipsis:before {
    content: "";
    float: left;
    width: 5px;
    height: 200px;
}
.ellipsis > *:first-child {
    float: right;
    width: 100%;
    margin-left: -5px;
}
.ellipsis:after {
    content: "\02026";
    box-sizing: content-box;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;
    float: right;
    position: relative;
    top: -25px;
    left: 100%;
    width: 3em;
    margin-left: -3em;
    padding-right: 5px;
    text-align: right;
    background-size: 100% 100%;/* 512x1 image,gradient for IE9. Transparent at 0% -> white at 50% -> white at 100%.*/
    background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAABCAMAAACfZeZEAAAABGdBTUEAALGPC/xhBQAAAwBQTFRF////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAA////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wDWRdwAAAP90Uk5TgsRjMZXhS30YrvDUP3Emow1YibnM9+ggOZxrBtpRRo94gxItwLOoX/vsHdA2yGgL8+TdKUK8VFufmHSGgAQWJNc9tk+rb5KMCA8aM0iwpWV6dwP9+fXuFerm3yMs0jDOysY8wr5FTldeoWKabgEJ8RATG+IeIdsn2NUqLjQ3OgBDumC3SbRMsVKsValZplydZpZpbJOQco2KdYeEe36BDAL8/vgHBfr2CvTyDu8R7esU6RcZ5ecc4+Af3iLcJSjZ1ivT0S/PMs3LNck4x8U7wz7Bv0G9RLtHuEq1TbJQr1OtVqqnWqRdoqBhnmSbZ5mXapRtcJGOc4t2eYiFfH9AS7qYlgAAARlJREFUKM9jqK9fEGS7VNrDI2+F/nyB1Z4Fa5UKN4TbbeLY7FW0Tatkp3jp7mj7vXzl+4yrDsYoVx+JYz7mXXNSp/a0RN25JMcLPP8umzRcTZW77tNyk63tdprzXdmO+2ZdD9MFe56Y9z3LUG96mcX02n/CW71JH6Qmf8px/cw77ZvVzB+BCj8D5vxhn/vXZh6D4uzf1rN+Cc347j79q/zUL25TPrJMfG/5LvuNZP8rixeZz/mf+vU+Vut+5NL5gPOeb/sd1dZbTs03hBuvmV5JuaRyMfk849nEM7qnEk6IHI8/qn049hB35QGHiv0yZXuMdkXtYC3ebrglcqvYxoj1muvC1nDlrzJYGbpcdHHIMo2FwYv+j3QAAOBSfkZYITwUAAAAAElFTkSuQmCC);
    background: -webkit-gradient(linear,left top,right top,
        from(rgba(255,255,255,0)),to(white),color-stop(50%,white));
        background: -moz-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
        background: -o-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
        background: -ms-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
        background: linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
    }

当然,作为一个纯粹的CSS解决方案意味着它也是一个非常复杂的解决方案,但它的工作干净而优雅。我将假设Javascript是不可能的,因为使用Javascript更容易实现(并且可以说更可降级)。

作为一个额外的奖励,有完整过程的downloadable zip file(如果你想了解它和所有),还有一个SASS mixin文件,这样你就可以将它折叠到你的过程中 - peasy。

希望这有帮助!

<强> http://www.mobify.com/blog/multiline-ellipsis-in-pure-css/

答案 2 :(得分:25)

看看这个纯粹的CSS版本:http://codepen.io/martinwolf/pen/qlFdp

display: -webkit-box;
max-width: 400px;
height: 109.2px;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.625;

答案 3 :(得分:8)

下面的Css应该可以解决问题。

在第二行之后,文本将包含...

line-height: 1em;
max-height: 2em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

答案 4 :(得分:5)

如果以上方法无效,请使用此功能

 display: -webkit-box;
 max-width: 100%;
 margin: 0 auto;
 -webkit-line-clamp: 2;
 /* autoprefixer: off */
 -webkit-box-orient: vertical;
 /* autoprefixer: on */
 overflow: hidden;
 text-overflow: ellipsis;

答案 5 :(得分:1)

我的解决方案重用了amcdnl,但我的后备包括使用文本容器的高度:

.my-caption h4 {
    display: -webkit-box;
    margin: 0 auto;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;

    height: 40px;/* Fallback for non-webkit */
}

答案 6 :(得分:1)

对于在 scss 中工作的人员,您需要在评论的开头添加!autoprefixer,以便将其保留用于postcss:

我遇到了这个问题,这就是为什么要在这里发布

line-height: 1em;
max-height: 2em;
display: -webkit-box;
/*! autoprefixer: off */
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

Reference

答案 7 :(得分:1)

根据我在stackoveflow中看到的答案,我创建了这个LESS mixin(use this link to generate the CSS code):

.max-lines(@lines: 3; @line-height: 1.2) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: @lines;
  line-height: @line-height;
  max-height: @line-height * @lines;
}

用法

.example-1 {
    .max-lines();
}

.example-2 {
    .max-lines(3);
}

.example-3 {
    .max-lines(3, 1.5);
}

答案 8 :(得分:0)

这是基于马汉拉梅建议的 Material-UI 淡化文本效果:

创建叠加样式
const useStyles = makeStyles((theme) =>
  createStyles({
    fadeText: {
      background: `linear-gradient( 180deg, #FFFFFF00, 0%, #FFFFFF06 30%, #FFFFFFFF 100%)`,
      pointerEvents: "none",
    }
  })
)
接下来在固定高度的嵌套 Box 组件上叠加渐变
<Grid container justify="center">
  <Grid item xs={8} sm={6} md={4}>
    <Box>
      <Box
        component="div"
        overflow="hidden"
        display="flex"
        flexDirection="column"
        fontFamily="Roboto"
        fontSize="body1.fontSize"
        fontWeight="fontWeightLight"
        textAlign="justify"
        height={['8rem']}
      >
        <Box display="flex">
          Lorem ipsum dolor sit amet, consectetur adipiscing
          elit, sed do eiusmod tempor incididunt ut labore
          et dolore magna aliqua. Ut enim ad minim veniam,
          quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure
          dolor in reprehenderit in voluptate velit esse
          cillum dolore eu fugiat nulla pariatur. Excepteur
          sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est
          laborum.
        </Box>
      </Box>
      <Box
        className={classes.fadeText}
        display="block"
        position="relative"
        top="-4rem"
        height="4rem"
      />
    </Box>
  </Grid>
</Grid>

工作演示:Codesandbox

MUI 的默认主题使用缩写的 CSS 颜色 (#FFF),因此如果您想根据当前主题设置渐变,您需要使用完整的六个字符变体来覆盖它们。

示例:使用 theme 设置渐变(例如基于浅色/深色主题):

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    fadeText: {
      background: `linear-gradient( 180deg, ${theme.palette.background.paper}00 0%, ${theme.palette.background.paper}06 30%, ${theme.palette.background.paper}FF 100%)`
    } 
  })
)

编辑:更新以包含 Tony Bogdanov 的建议

答案 9 :(得分:0)

您可以使用溶解效果代替省略号,纯CSS并看起来更专业:

    <div style="width: 293px; height:48px; overflow: hidden; ">
        More than two line of text goes here-More than two line of text goes here
    </div>
    <div style="position: relative; top: -24px; width: 293px; height:24px; 
             background: linear-gradient(90deg, rgba(255,0,0,0) 40%, rgba(255,255,255,1) 99%);">
    </div>

这里我假设您的背景色是白色。

答案 10 :(得分:0)

在我的有角度的应用程序中,以下样式对我起作用,以使省略号在第二行上的文本 上达到:

 <div style="height:45px; overflow: hidden; position: relative;">
     <span class=" block h6 font-semibold clear" style="overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box; 
        line-height: 20px; /* fallback */
        max-height: 40px; /* fallback */
        -webkit-line-clamp: 2; /* number of lines to show */
        -webkit-box-orient: vertical;">
        {{ event?.name}} </span>
 </div>

希望它可以帮助某人。

答案 11 :(得分:0)

在几乎所有浏览器中都可以使用几行,但是在Firefox和IE中不会显示省略号(3点)。演示-http://jsfiddle.net/ahzo4b91/1/

div {
width: 300px;
height: 2.8em;
line-height: 1.4em;
display: flex;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden; 
}

答案 12 :(得分:0)

结合两个类看起来更优雅。如果只需要一行,则可以删除two-lines类:

.ellipse {
          white-space: nowrap;
          display:inline-block;
          overflow: hidden;
          text-overflow: ellipsis;
       }
      .two-lines {
          -webkit-line-clamp: 2;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          white-space: normal;
      }
      .width{
          width:100px;
          border:1px solid hotpink;
      }
        <span class='width ellipse'>
          some texts some texts some texts some texts some texts some texts some texts
       </span>

       <span class='width ellipse two-lines'>
          some texts some texts some texts some texts some texts some texts some texts
       </span>

答案 13 :(得分:0)

这是一个使用jQuery管理省略号的简单脚本。 它检查元素的实际高度,并创建隐藏的原始节点和截断的节点。 当用户点击它时,在两个版本之间切换。

其中一个很大的好处就是&#34;省略号&#34;正如预期的那样,接近最后一个字。

如果使用纯CSS解决方案,则三个点看起来与最后一个单词相距很远。

&#13;
&#13;
valgrind
&#13;
$ valgrind ./bin/readprn <dat/namesfirst.txt
==28428== Memcheck, a memory error detector
==28428== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==28428== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==28428== Command: ./bin/readprn
==28428==
a[  0] : adam
<snip>
a[ 24] : frank
==28428==
==28428== HEAP SUMMARY:
==28428==     in use at exit: 0 bytes in 0 blocks
==28428==   total heap usage: 26 allocs, 26 frees, 413 bytes allocated
==28428==
==28428== All heap blocks were freed -- no leaks are possible
==28428==
==28428== For counts of detected and suppressed errors, rerun with: -v
==28428== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
&#13;
function manageShortMessages() {

        $('.myLongVerticalText').each(function () {
            if ($(this)[0].scrollHeight > $(this)[0].clientHeight)
                $(this).addClass('ellipsis short');
        });

        $('.myLongVerticalText.ellipsis').each(function () {
            var original = $(this).clone().addClass('original notruncation').removeClass('short').hide();
            $(this).after(original);

            //debugger;
            var shortText = '';
            shortText = $(this).html().trim().substring(0, 60) + '...';
            $(this).html(shortText);
        });
        
        $('.myLongVerticalText.ellipsis').click(function () {
            $(this).hide();

            if ($(this).hasClass('original'))
            {
                $(this).parent().find('.short').show();
            }
            else
            {
                $(this).parent().find('.original').show();
            }
        });
    }
	
  manageShortMessages();
&#13;
&#13;
&#13;

答案 14 :(得分:0)

          text-overflow: ellipsis;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          line-height: 36px;
          max-height: 18px;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;

我找到了线夹和线高的组合:D

答案 15 :(得分:-1)

这是一个完全黑客攻击,但它确实有效:

http://jsfiddle.net/2wPNg/

div {
    width: 30%;
    float: left;
    margin-right: 2%;
    height: 94px;
    overflow: hidden;
    position: relative;
}

div:after {
     display: block;
      content: '...';
      width: 1em;
  height: 1.5em;
  background: #fff;
  position: absolute;
  bottom: -6px;
  right: 0;
    }

它确实存在问题......它可能会笨拙地切断一封信,并且在响应式网站上可能会有一些奇怪的结果。

答案 16 :(得分:-3)

不确定您的目标是什么,但是您希望文本出现在第二行吗?

这是你的jsFiddle:http://jsfiddle.net/8kvWX/4/刚刚删除了以下内容:

     white-space:nowrap;  

我不确定这是不是你想要的。

此致