Programming

CSS를 사용하여 텍스트 길이를 n 줄로 제한

procodes 2020. 2. 17. 22:25
반응형

CSS를 사용하여 텍스트 길이를 n 줄로 제한


CSS를 사용하여 텍스트 길이를 "n"줄로 제한 할 수 있습니까 (또는 세로로 넘칠 때 잘라 내기).

text-overflow: ellipsis; 한 줄짜리 텍스트에서만 작동합니다.

원문 :

pellentesque tincidunt
elit purus lectus, vel ut aliquet, elementum nunc
nunc rhoncus placerat urna의 Ultrices natoque mus mattis, aliquam, cras ! sed sed! 페티 부스 터 피스
무스 tincidunt! Dapibus sed aenean, 마그나 사지 티스, 로렐 벨리트

원하는 출력 (2 줄) :

Ultrices natoque mus mattis, aliquam,
pellentesque tincidunt elit purus lectus, vel ut aliquet, elementum ...


방법이 있지만 웹킷 전용입니다. 그러나 이것을 line-height: X;, 및와 결합하면 max-height: X*N;타원없이 다른 브라우저에서도 작동합니다.

.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 */
}

데모 : http://jsfiddle.net/csYjC/1131/


할 수있는 일은 다음과 같습니다.

.max-lines {
  display: block; /* or inline-block */
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em;
  line-height: 1.8em;
}

여기서 max-height:= line-height:× <number-of-lines>in em입니다.


크로스 브라우저 솔루션 작동

이 문제는 몇 년 동안 우리 모두를 괴롭 혔습니다.

모든 경우에 도움이되도록 CSS 전용 접근법과 CSS주의 문제가있는 경우 jQuery 접근법을 배치했습니다.

다음 은 몇 가지 사소한 경고와 함께 모든 상황에서 작동 하는 CSS 전용 솔루션입니다.

기본 사항은 간단하고 스팬 오버플로를 숨기고 Eugene Xa가 제안한 선 높이를 기준으로 최대 높이를 설정합니다.

그런 다음 포함 div 뒤에 생략 부호를 배치하는 의사 클래스가 있습니다.

경고

이 솔루션은 필요에 관계없이 항상 줄임표를 배치합니다.

마지막 줄이 끝 문장으로 끝나면 네 개의 점으로 끝납니다 ....

정렬 된 텍스트 정렬에 만족해야합니다.

줄임표는 텍스트의 오른쪽에 있으며 느슨해 보일 수 있습니다.

코드 + 스 니펫

jsfiddle

.text {
  position: relative;
  font-size: 14px;
  color: black;
  width: 250px; /* Could be anything you like. */
}

.text-concat {
  position: relative;
  display: inline-block;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */
  line-height: 1.2em;
  text-align:justify;
}

.text.ellipsis::after {
  content: "...";
  position: absolute;
  right: -12px; 
  bottom: 4px;
}

/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
<div class="text ellipsis">
  <span class="text-concat">
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in.

Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri.
  </span>
</div>

jQuery 접근

제 생각에는 이것이 최선의 해결책이지만 모든 사람이 JS를 사용할 수있는 것은 아닙니다. 기본적으로 jQuery는 .text 요소를 확인하고 사전 설정된 최대 var보다 많은 문자가 있으면 나머지 부분을 잘라내어 줄임표를 추가합니다.

이 접근법에 대한주의 사항은 없지만이 코드 예제는 기본 아이디어를 보여주기위한 것입니다. 두 가지 이유로 개선하지 않고 프로덕션에서는 사용하지 않을 것입니다.

1) .text elems의 내부 HTML을 다시 작성합니다. 필요하든 없든 2) 내부 HTML에 중첩 된 요소가 없는지 확인하는 테스트는 없으므로 저자가 .text를 올바르게 사용하는 데 많은 의존합니다.

편집

캐치 @markzzz 주셔서 감사합니다

코드 및 스 니펫

jsfiddle

setTimeout(function()
{
	var max = 200;
  var tot, str;
  $('.text').each(function() {
  	str = String($(this).html());
  	tot = str.length;
    str = (tot <= max)
    	? str
      : str.substring(0,(max + 1))+"...";
    $(this).html(str);
  });
},500); // Delayed for example only.
.text {
  position: relative;
  font-size: 14px;
  color: black;
  font-family: sans-serif;
  width: 250px; /* Could be anything you like. */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text">
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young.
</p>

<p class="text">
Old men tend to forget what thought was like in their youth;
</p>
 <!-- Working Cross-browser Solution

This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->


내가 볼 수있는 한, 이것은 사용하는 것만 가능 height: (some em value); overflow: hidden하며 심지어 ...는 결국 에는 환상 갖지 못할 것 입니다.

이것이 옵션이 아닌 경우 일부 서버 측 사전 처리 (텍스트 흐름을 안정적으로 예측하기가 어렵 기 때문에) 또는 jQuery (가능하지만 복잡 할 수 있음)가 없으면 불가능하다고 생각합니다.


이 스레드 의 해결책 은 jquery 플러그인 dotdotdot 를 사용하는 입니다. CSS 솔루션은 아니지만 "더 읽기"링크, 동적 크기 조정 등을위한 많은 옵션을 제공합니다.


다음 CSS 클래스는 두 줄의 줄임표를 얻는 데 도움이되었습니다.

  .two-line-ellipsis {
        padding-left:2vw;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 325px;
        line-height: 25px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        padding-top: 15px;
    }

현재는 할 수 없지만 앞으로는를 사용할 수 있습니다 text-overflow:ellipis-lastline. 현재 Opera 10.60+에서 공급 업체 접두사를 사용할 수 있습니다.


잘 작동하는 솔루션이 있지만 대신 타원이 그라디언트를 사용합니다. 동적 텍스트가있을 때 작동하므로 타원이 필요할 정도로 오래 지속되는지 알 수 없습니다. 장점은 JavaScript 계산을 수행 할 필요가 없으며 테이블 셀을 포함한 가변 폭 컨테이너에서 작동하며 브라우저 간이라는 것입니다. 두 개의 추가 div를 사용하지만 구현하기가 매우 쉽습니다.

마크 업 :

<td>
    <div class="fade-container" title="content goes here">
         content goes here
         <div class="fade">
    </div>
</td>

CSS :

.fade-container { /*two lines*/
    overflow: hidden;
    position: relative;
    line-height: 18px; 
    /* height must be a multiple of line-height for how many rows you want to show (height = line-height x rows) */
    height: 36px;
    -ms-hyphens: auto;
    -webkit-hyphens: auto;
    hyphens: auto;
    word-wrap: break-word;
}

.fade {
        position: absolute;
        top: 50%;/* only cover the last line. If this wrapped to 3 lines it would be 33% or the height of one line */
        right: 0;
        bottom: 0;
        width: 26px;
        background: linear-gradient(to right,  rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
}

블로그 게시물 : http://salzerdesign.com/blog/?p=453

예제 페이지 : http://salzerdesign.com/test/fade.html


나는 정말로 라인 클램프를 좋아하지만 파이어 폭스를 지원하지 않습니다. 그래서 나는 수학 계산으로 가서 오버플로를 숨 깁니다.

.body-content.body-overflow-hidden h5 {
    max-height: 62px;/* font-size * line-height * lines-to-show(4 in this case) 63px if you go with jquery */
    overflow: hidden;
}
.body-content h5 {
    font-size: 14px; /* need to know this*/
    line-height:1,1; /*and this*/
}

이제 jQuery를 통해 링크를 사용 하여이 클래스를 제거하고 추가한다고 말하면 최대 높이가 63px가되도록 추가 픽셀이 필요합니다. 높이보다 큰 경우 매번 확인해야하기 때문입니다. 62px이지만 4 줄의 경우 거짓 사실이 표시되므로 추가 픽셀 로이 문제를 해결하고 추가 문제가 발생하지 않습니다.

이 예제를 위해 커피 스크립트를 붙여 넣고 기본적으로 숨겨져있는 링크를 사용합니다. 읽기 및 읽기가없는 클래스를 사용하면 오버플로가 필요하지 않은 본문을 제거하고 본문을 제거합니다 오버플로 클래스

jQuery ->

    $('.read-more').each ->
        if $(this).parent().find("h5").height() < 63
             $(this).parent().removeClass("body-overflow-hidden").find(".read-less").remove()
             $(this).remove()
        else
            $(this).show()

    $('.read-more').click (event) ->
        event.preventDefault()
        $(this).parent().removeClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-less').show()

    $('.read-less').click (event) ->
        event.preventDefault()
        $(this).parent().addClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-more').show()

letter당신이 그렇게 할 수있는 각각에 집중하고 싶다면 , 나는 질문을 참조합니다

function truncate(source, size) {
  return source.length > size ? source.slice(0, size - 1) + "…" : source;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

각각에 집중하고 싶다면 word+ 공간처럼 할 수 있습니다.

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT 
    const newTitle = [];
    if (title.length > limit) {
        title.split(' ').reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join(' ') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

당신이 각각에 집중하고 싶다면 word공간없이 그처럼 할 수 있습니다.

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT 
    const newTitle = [];
    if (title.length > limit) {
        Array.prototype.slice.call(title).reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join('') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);


.class{
   word-break: break-word;
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   line-height: 16px; /* fallback */
   max-height: 32px; /* fallback */
   -webkit-line-clamp: 2; /* number of lines to show */
   -webkit-box-orient: vertical;
}

기본 예제 코드, 코드 학습이 쉽습니다. 스타일 CSS 주석을 확인하십시오.

table tr {
  display: flex;
}
table tr td {
  /* start */
  display: inline-block; /* <- Prevent <tr> in a display css */
  text-overflow: ellipsis;
  white-space: nowrap;
  /* end */
  padding: 10px;
  width: 150px; /* Space size limit */
  border: 1px solid black;
  overflow: hidden;
}
<table>
  <tbody>
    <tr>
      <td>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus.
      </td>
      <td>
        Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut
        nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat.
      </td>
      <td>
        Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien.
        Ut dictum massa mi, sit amet interdum mi bibendum nec.
      </td>
    </tr>
    <tr>
      <td>
        Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis
        nibh dui et erat.
      </td>
      <td>
        Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est
        aliquet.
      </td>
      <td>
        Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus.
        Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo.
      </td>
    </tr>
  </tbody>
</table>


나는 이것을 둘러 보았지만 웹 사이트가 PHP를 사용한다는 것을 알았습니다. 텍스트 입력에 트림 기능을 사용하고 최대 길이로 재생하지 않는 이유는 무엇입니까? ...

다음은 PHP를 사용하는 사람들에게 가능한 해결책입니다 : http://ideone.com/PsTaI

<?php
$s = "In the beginning there was a tree.";
$max_length = 10;

if (strlen($s) > $max_length)
{
   $offset = ($max_length - 3) - strlen($s);
   $s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}

echo $s;
?>

참고 URL : https://stackoverflow.com/questions/3922739/limit-text-length-to-n-lines-using-css

반응형