div 내에서 두 줄로만 텍스트 감싸기


85

특정 너비의 div 내에서 두 줄로만 텍스트를 감싸고 싶습니다. 텍스트가 두 줄의 길이를 초과하면 생략 표시를 표시하고 싶습니다. CSS를 사용하는 방법이 있습니까?

예 :

Sample text showing wrapping
of text in only two line...

감사

답변:


142

당신은 설정하면 텍스트의 두 줄 출력을 제한하면, CSS 가능합니다 line-heightheight요소의, 그리고 세트 overflow:hidden;:

#someDiv {
    line-height: 1.5em;
    height: 3em;       /* height is 2x line-height, so two lines will display */
    overflow: hidden;  /* prevents extra lines from being visible */
}

--- jsFiddle 데모 ---

또는 CSS text-overflowwhite-space속성을 사용하여 타원을 추가 할 수 있지만 이는 한 줄에서만 작동하는 것처럼 보입니다.

#someDiv {
    line-height: 1.5em;
    height: 3em;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
}

그리고 데모 :

--- jsFiddle 데모 ---

여러 줄의 텍스트와 줄임표를 모두 달성하는 것이 자바 스크립트의 영역 인 것처럼 보입니다.


11
/ : 나는 한 줄 어떤 이유에서가는 참조
SearchForKnowledge

7
두 번째 예에는 요청 된 솔루션에 두 줄이 필요한 경우 한 줄만 있습니다.
goyote

세 번째 예제는 Chrome 및 Firefox에서 테스트 된 저에게 적합하지 않습니다.
Oliver Lorton

1
깨진 예에서 white-space: nowrap;주석을 달면 작동합니다.
Wilt

42

또 다른 간단하고 빠른 솔루션

.giveMeEllipsis {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: N; /* number of lines to show */
   line-height: X;        /* fallback */
   max-height: X*N;       /* fallback */
}

원래 질문과 답변에 대한 참조는 여기에 있습니다.


3
놀라운 솔루션! 나는 완전히 그것을 테스트하지 않은,하지만 첫 번째 시도에서이 아주 잘 작동
Gambai을

4
@vinesh이 솔루션이 불타고 있습니다! 🔥
PhillipJacobs

보인다 box-orient이다 사용되지 않거나 쓸모 .
Greg Herbowicz

공장! a mat-card-contentin a 내부 테스트flexbox container
faizanjehangir

17

내가 본 것 중 가장 좋은 것은 CSS 전용이고 반응 형인 Mobify 개발자 블로그-CSS Ellipsis : How to Manage Multi-Line Ellipsis in Pure CSS :

JS 바이올린 예

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

HTML :

<div class="ellipsis">
    <div class="blah">
        <p>Call me Ishmael. Some years ago &ndash; never mind how long precisely &ndash; 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 &ndash; then, I account it high time to get to sea as soon as I can.</p>
    </div>
</div>

지금까지 본 최고의 솔루션입니다. 바이올린에서 높이 (200px) 변수를 줄여야 할 수 있습니다. 화면 크기 때문에 처음에는 텍스트가 오버플로되지 않았습니다.
Mike Fuchs

14

CSS 전용 솔루션 text-overflow: ellipsis은 한 줄에만 적용되므로이 경로를 사용할 수 없습니다.

.yourdiv {

    line-height: 1.5em; /* Sets line height to 1.5 times text size */
    height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
    width: 100%; /* Use whatever width you want */
    white-space: normal; /* Wrap lines of text */
    overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
    text-overflow: ellipsis; /* Ellipses (cross-browser) */
    -o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}

jQuery에 http://tpgblog.com/threedots/ 를 사용해 보셨습니까 ?


내가 언급했듯이 타원을 여러 줄의 텍스트와 결합하는 것은 적어도 Chrome에서는 작동하지 않는 것 같습니다.
jackwanders

이것은 내가 추가 한 후 내 현재의 문제에서 근무 : display: blockmin-height: 13pxmax-height: 26pxA의 높이를 설정<td>
언더 벌스

8

Webkit 용 CSS 전용 솔루션

// Only for DEMO
$(function() {

  $('#toggleWidth').on('click', function(e) {

    $('.multiLineLabel').toggleClass('maxWidth');

  });

})
.multiLineLabel {
  display: inline-block;
  box-sizing: border-box;
  white-space: pre-line;
  word-wrap: break-word;
}

.multiLineLabel .textMaxLine {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}


/* Only for DEMO */

.multiLineLabel.maxWidth {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multiLineLabel">
  <span class="textMaxLine">This text is going to wrap automatically in 2 lines in case the width of the element is not sufficiently wide.</span>
</div>
<br/>
<button id="toggleWidth">Toggle Width</button>


이것이 최상의 솔루션이며 답변으로 표시되어야합니다. 감사.
QMaster

6

CSS 만

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;


4

일반적으로 한 줄 자르기는 매우 간단합니다.

.truncate-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

두 줄 자르기는 좀 더 까다 롭지 만이 예제는 sass에있는 css로 수행 할 수 있습니다.

@mixin multiLineEllipsis($lineHeight: 1.2rem, $lineCount: 2, $bgColor: white, $padding-right: 0.3125rem, $width: 1rem, $ellipsis-right: 0) {
  overflow: hidden; /* hide text if it is more than $lineCount lines  */
  position: relative; /* for set '...' in absolute position */
  line-height: $lineHeight; /* use this value to count block height */
  max-height: $lineHeight * $lineCount; /* max-height = line-height * lines max number */
  padding-right: $padding-right; /* place for '...' */
  white-space: normal; /* overwrite any white-space styles */
  word-break: break-all; /* will break each letter in word */
  text-overflow: ellipsis; /* show ellipsis if text is broken */

  &::before {
    content: '...'; /* create the '...'' points in the end */
    position: absolute;
    right: $ellipsis-right;
    bottom: 0;
  }

  &::after {
    content: ''; /* hide '...'' if we have text, which is less than or equal to max lines and add $bgColor */
    position: absolute;
    right: 0;
    width: $width;
    height: 1rem * $lineCount;
    margin-top: 0.2rem;
    background: $bgColor; /* because we are cutting off the diff we need to add the color back. */
  }
}

2

http://jsfiddle.net/SWcCt/를 참조하십시오 .

다음 line-height의 절반 만 설정하면됩니다 height.

line-height:20px;
height:40px;

물론 text-overflow: ellipsis작업을하려면 다음이 필요합니다.

overflow:hidden;
white-space: pre;

이 솔루션은 유연하지 않으며 소스 텍스트에서 수동 줄 바꿈이 필요합니다. 참고 jsfiddle.net/SWcCt/282 각 상자는 한 줄의 텍스트가 포함되어 있습니다. 원하는 솔루션은 두 번째 줄 끝에 줄임표가있는 것을 제외하고 jsfiddle.net/SWcCt/283 의 두 번째 상자와 같습니다 .
Joshua Coady

@JoshuaCoady 좋은 지적이지만 text-overflow: ellipsis라인 상자를 넘치는 인라인 상자에서만 작동합니다. 없이는 white-space: pre다음 줄 상자로 이동합니다. 그리고 수동 줄 바꿈이 필요합니다. 완벽한 해결책은 없다고 생각합니다.
Oriol


0

@Asiddeen bn Muhammad의 솔루션은 CSS를 약간 수정하여 나를 위해 일했습니다.

    .text {
 line-height: 1.5;
  height: 6em; 
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: block;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
 }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.