두 줄의 텍스트 오버플로 줄임표


117

CSS 규칙 조합을 사용하여 오버플로 할 때 (부모 경계를 벗어날 때) 줄임표 (...)로 텍스트를 끝낼 수 있다는 것을 알고 있습니다.

같은 효과를내는 것이 가능하지만 (아니오라고 말 하셔도됩니다) 텍스트가 한 줄 이상으로 줄 바꿈되도록 할 수 있습니까?

여기에 데모가 있습니다.

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

보시다시피 텍스트가 div의 너비보다 넓어지면 줄임표로 끝납니다. 그러나 텍스트를 두 번째 줄에서 줄 바꿈하고 계속 진행할 수있는 충분한 공간이 있습니다. 이 white-space: nowrap작업은 줄임표가 작동하는 데 필요한에 의해 중단됩니다 .

어떤 아이디어?

추신 : JS 솔루션이 없습니다. 가능하면 순수한 CSS입니다.


무엇이 "공간이있다"를 결정합니까? 설정된 픽셀의 글꼴 높이를 포함한 모든 것이 있습니까? 최종 사용자가 브라우저에서 글꼴 크기를 늘리면 어떻게됩니까?
Joel Etherton 2013


@JoelEtherton 나는 그것이 브라우저가 결정할 일이라고 생각하고 예, 내 경우에는 모든 것이 픽셀 단위입니다.
Tony Bogdanov 2013

이것은 좋은 해결책이 될 수 있습니다 : stackoverflow.com/questions/6222616/…
ivy

이것은 정말 좋은 읽기입니다 hackingui.com/front-end/...
anandharshan

답변:


31

나는 확실히 당신이 본 경우 아니에요 본을 하지만, 크리스 Coyier의 우수한 CSS-Tricks.com이 잠시 뒤로 링크를 게시 정확히 당신이 무엇을 추구 수행 순수 CSS의 솔루션입니다.

(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가 문제가되지 않는다고 가정합니다.

추가 보너스로 전체 프로세스의 다운로드 가능한 zip 파일 (모든 것을 이해하려는 경우)이 있지만 SASS 믹스 인 파일도있어 프로세스에 쉽게 접을 수 있습니다.

도움이 되었기를 바랍니다!

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


Android 폰에서 Codepen 링크를 클릭했는데 Firefox에서 작동했습니다. 어떤 플랫폼 / 브라우저에서 작동하지 않습니까?
dashard

uploady.com/#!/download/kAwBXv1CqXg/PU68wrP6QzGgydlS 크롬을 사용하고 있으며 미리보기에 줄임표가 없습니다. 텍스트 줄을 계속 추가하면 아무 일도 일어나지 않습니다. 몇 줄 후에 줄임표가 표시되기 시작합니까?
coding_idiot 2015 년

게시 한 업로드 링크에서 텍스트가 아직 컨테이너에 넘치지 않은 것이 분명합니다. 줄임표가 나타나기 전에 고정 컨테이너가 표시하려면 텍스트가 너무 많아야합니다. 효과를 보려면 텍스트를 계속 추가하십시오.
dashard

@ MarcosPérezGude-놀랍지 않습니다. >> "물론 순수한 CSS 솔루션이라는 것은 매우 복잡한 솔루션이라는 것을 의미합니다…"<<
dashard

137

쉬운 CSS 속성이 트릭을 할 수 있습니다. 다음은 3 줄 줄임표입니다.

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

15
이것은 firefox에서 작동하지 않습니다. 단지 크롬, 사파리, 오페라
anyavacy

1
caniuse 에 따르면 "다른 브라우저가 속성을있는 그대로 지원할 가능성은 낮습니다"라고 말합니다. 그래서 머리 위로.
Matan Bobi

친구를 부드럽게 .. 매우 도움이
발렌티노 페레이라에게

4
Firefox에서도 gr8 작업
Nisharg Shah

4
지금 큰 지원을받는 것 같습니다 : caniuse.com/#search=line-clamp
Joao

52

이 순수한 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;

7
정말 멋지다, 너무 나쁘다. 그것은 웹킷 뿐이다. 다음은이 문제에 흥미로운 기사는 다음과 같습니다 css-tricks.com/line-clampin
토니 보그

왜 두 가지 text-overflowdisplay규칙 을 선언 합니까?
j08691

큰 WoooW. 라인 클램프 전에는 본 적이 없습니다
Mike Aron

1
참고로, 이것은 요즘 Firefox에서도 잘 작동합니다. 훌륭한 솔루션!
Athoxx

단 하나의 질문, 한 줄 또는 두 줄의 텍스트가 중앙에 배치되기를 원할 때 어떻게해야하나요? display flex를 추가하면 줄임표가
없어지고

10

아래 CSS가 트릭을 수행해야합니다.

두 번째 줄 뒤에는 텍스트에 ...

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

이것은 잘 작동했지만 추가해야했습니다overflow:hidden
timhysniu

3

위의 방법이 작동하지 않는 경우 이것을 사용하십시오.

 display: block;
 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;

2

내 솔루션은 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 */
}

-webkit-line-clampIE11, Edge 또는 Firefox에서는 작동하지 않습니다.
Gaʀʀʏ

@Garry, 당신이 맞습니다. 당시에는 JS 수정이 필요했지만 이제는 정상적으로 작동합니다. caniuse.com/#search=webkit-line-clamp
VincentPerrin.com 2010 년

1

stackoveflow에서 본 답변을 바탕 으로이 LESS 믹스 인을 만들었습니다 ( 이 링크를 사용하여 CSS 코드 생성 ).

.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);
}

1

두 클래스를 결합하는 것이 더 우아해 보입니다. 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>


1

몇 줄로 제한하면 거의 모든 브라우저에서 작동하지만 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; 
}

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;

라인 클램프와 라인 높이 작업의 콤보를 찾았습니다.


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>

누군가에게 도움이되기를 바랍니다.


0

scss 에서 작업하는 사람들 !autoprefixer의 경우 postcss에 대해 유지되도록 주석의 시작 부분 에 추가해야합니다 .

나는 그 문제에 직면했기 때문에 여기에 게시했습니다.

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

참고


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>

여기에서는 배경색이 흰색이라고 가정했습니다.


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

문제가 있습니다 .... 문자가 어색하게 잘릴 수 있으며 반응 형 사이트에서 이상한 결과가 나타날 수 있습니다.


5
내용이 더 작 으면 끝에 '...'를 추가하기 때문에 이것은 올바른 해결책이 아닙니다. Fiddle : jsfiddle.net/2wPNg
Sachin

-1

다음은 jQuery를 사용하여 줄임표를 관리하는 간단한 스크립트입니다. 요소의 실제 높이를 검사하고 숨겨진 원래 노드와 잘린 노드를 만듭니다. 사용자가 클릭하면 두 버전간에 전환됩니다.

큰 이점 중 하나는 예상대로 "줄임표"가 마지막 단어 근처에 있다는 것입니다.

순수한 CSS 솔루션을 사용하는 경우 세 개의 점이 마지막 단어에서 멀리 떨어져 나타납니다.

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();
div {
 border:1px solid red;
 margin:10px;
}

div.myLongVerticalText {
  height:30px;
  width:450px;
}

div.myLongVerticalText.ellipsis {
 cursor:pointer;
}

div.myLongVerticalText.original {
  display:inline-block;
  height:inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="myLongVerticalText">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sit amet quam hendrerit, sagittis augue vel, placerat erat. Aliquam varius porta posuere. Aliquam erat volutpat. Phasellus ullamcorper malesuada bibendum. Etiam fringilla, massa vitae pulvinar vehicula, augue orci mollis lorem, laoreet viverra massa eros id est. Phasellus suscipit pulvinar consectetur. Proin dignissim egestas erat at feugiat. Aenean eu consectetur erat. Nullam condimentum turpis eu tristique malesuada.

Aenean sagittis ex sagittis ullamcorper auctor. Sed varius commodo dui, nec consectetur ante condimentum et. Donec nec blandit mi, vitae blandit elit. Phasellus efficitur ornare est facilisis commodo. Donec convallis nunc sed mauris vehicula, non faucibus neque vehicula. Donec scelerisque luctus dui eu commodo. Integer eu quam sit amet dui tincidunt pharetra eu ac quam. Quisque tempus pellentesque hendrerit. Sed orci quam, posuere eu feugiat at, congue sed felis. In ut lectus gravida, volutpat urna vitae, cursus justo. Nam suscipit est ac accumsan consectetur. Donec rhoncus placerat metus, ut elementum massa facilisis eget. Donec at arcu ac magna viverra tincidunt.
</div>


<div class="myLongVerticalText">
One Line Lorem ipsum dolor sit amet.  
</div>
</body>


이 솔루션에 반대하는 경우 여기에 이유를 설명해 주시면 감사하겠습니다.
Matteo Conta

1
OP는 CSS 솔루션을 요청했고 jQuery를 제공 했습니까?
dashard

나는 자바 스크립트가 없다는 것이 강력한 요구 사항이라는 것을 놓쳤다. 필자의 경우 순수한 CSS 솔루션은 렌더링 문제를 제시했고, jQuery 솔루션은 최종 렌더링과 줄임표 위치에 대한 더 많은 제어를 제공했습니다.
Matteo Conta

절대적으로 동의합니다. 내 대답에서 나는 이것이 JS로 달성하기가 무한히 쉽다는 것을 지적했습니다.
dashard

-3

목표가 무엇인지 확실하지 않지만 두 번째 줄에 텍스트를 표시 하시겠습니까?

다음은 jsFiddle입니다. http://jsfiddle.net/8kvWX/4/ 방금 다음을 제거했습니다.

     white-space:nowrap;  

이것이 당신이 찾고있는 것인지 아닌지 확실하지 않습니다.

문안 인사,


1
그는 두 번째 줄 끝에 줄임표를 원하는데, 자바 스크립트 없이는 그렇게 쉽지 않습니다.
Marc Audet 2013

@MarcAudet 정확히 :)
토니 보그

맞아요, 두 번째 줄에 줄을 요청하는 다른 사람을 찾았고 그의 CSS는 당신의 것과 거의 같았지만 클래스는 대신 ul 태그를 가리 켰습니다. 어쨌든, 미안 해요 토니. 다시 한번 살펴보고 성공하면 답변을 업데이트하겠습니다.
Mee

가장 좋은 해결책은 @Itay Gal의 솔루션이라고 생각합니다. 내가 본 것 중 하나가 작동하고 있습니다.
Mee
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.