CSS에서 최대 문자 길이 설정
저는 학교를 위해 대응하는 웹사이트를 만들고 있고, 제 질문은 다음과 같습니다.
내 웹 사이트(75자 정도)에서 문장의 최대 문자 길이(CSS 포함)를 설정하는 방법은 무엇입니까? 화면이 매우 클 때 문장이 75자 이상으로 진행되지 않습니다.
최대 너비를 시도해 보았지만 배치가 엉망입니다.저는 플렉스박스와 미디어 쿼리를 사용하여 응답성을 높이고 있습니다.
을 은 할 은 을 할 max-widthellipsis 식으로
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
예:
.wrapper {
padding: 20px;
background: #eaeaea;
max-width: 400px;
margin: 50px auto;
}
.demo-1 {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
.demo-2 {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 150px;
}
<div class="wrapper">
<p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
<div class="wrapper">
<p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
줄 의 을 을 의 flex◦ 한예.세 행에 잘라내기가 있는 예제.
p {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
예:
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!</p>
의 CSS '이' 의 CSS value.ch.
이 단위는 요소의 글꼴에서 글리프 '0'(0, 유니코드 문자 U+0030)의 너비, 또는 더 정확하게는 사전 측정을 나타냅니다.
이것은 여러분이 원하는 것과 비슷할 것입니다.
p {
overflow: hidden;
max-width: 75ch;
white-space: nowrap;
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque.</p>
최대 너비로 설정한 후 자르기 문자를 사용해 보십시오.나는 이 경우에 75ch를 사용했습니다.
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 75ch;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc.</p>
여러 줄 잘라내기의 경우 링크를 따라주시기 바랍니다.
예: https://codepen.io/srekoble/pen/EgmyxV
우리는 이것을 위해 웹킷 CSS를 사용할 것입니다.간단히 말해 WebKit은 사파리/크롬용 HTML/CSS 웹 브라우저 렌더링 엔진입니다.모든 브라우저가 HTML/CSS 웹 페이지를 그리기 위한 렌더링 엔진을 통해 지원되므로 브라우저에 따라 달라질 수 있습니다.
예제 코드:
.limited-text{
white-space: nowrap;
width: 400px;
overflow: hidden;
text-overflow: ellipsis;
}
<p class="limited-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
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에서는 불가능합니다, 자바스크립트를 이용하셔야 합니다.p의 너비를 최대 30자로 설정할 수 있고 다음 글자는 자동으로 내려오지만 이 역시 정확하지 않고 대문자로 표시되면 달라질 것입니다.
HTML
<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>
jQuery
var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
$(p).text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
CSS
#dash {
width: 400px;
height: 60px;
overflow: hidden;
}
#dash p {
padding: 10px;
margin: 0;
}
결과
로렘립스 섬 돌로르 시테, 콘세테투르 지방질 엘리트.프로니시 리굴라, 대피버스 볼럿팻 시테, 매티스...
현대 CSS 그리드 앤서
CodePen에서 완전히 작동하는 코드를 봅니다.다음과 같은 HTML이 주어지면:
<div class="container">
<p>Several paragraphs of text...</p>
</div>
CSS Grid를 사용하여 3개의 열을 만들고 컨테이너에 우리의 단락이 포함된 가운데 열에 대해 최대 70자의 너비를 취하도록 지시할 수 있습니다.
.container
{
display: grid;
grid-template-columns: 1fr, 70ch 1fr;
}
p {
grid-column: 2 / 3;
}
다음과 같은 모습입니다(CodePen에서 완벽하게 작동하는 예를 확인하십시오).
다음은 minmax를 사용하여 값의 범위를 설정할 수 있는 다른 예입니다.작은 화면에서는 너비가 50자로 설정되고 큰 화면에서는 너비가 70자로 설정됩니다.
.container
{
display: grid;
grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}
p {
grid-column: 2 / 3;
}
자르는 여러 줄 문자에 대한 순수 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;
}
이 게시물은 CSS 솔루션을 위한 것이지만 게시물이 꽤 오래되어 다른 사람들이 이 문제에 걸려 Angular 4+와 같은 현대적인 JS 프레임워크를 사용하는 경우 CSS를 가지고 장난칠 필요 없이 Angular Pipes를 통해 이를 수행할 수 있는 간단한 방법이 있습니다.
이 작업을 수행하는 데에는 아마도 "반응" 또는 "뷰" 방식이 있을 것입니다.이것은 단지 그것이 틀 안에서 어떻게 이루어질 수 있는지를 보여주기 위한 것입니다.
잘라내기-text.pipe.ts
/**
* Helper to truncate text using JS in view only.
*
* This is pretty difficult to do reliably with CSS, especially when there are
* multiple lines.
*
* Example: {{ value | truncateText:maxLength }} or {{ value | truncateText:45 }}
*
* If maxLength is not provided, the value will be returned without any truncating. If the
* text is shorter than the maxLength, the text will be returned untouched. If the text is greater
* than the maxLength, the text will be returned with 3 characters less than the max length plus
* some ellipsis at the end to indicate truncation.
*
* For example: some really long text I won't bother writing it all ha...
*/
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
transform(value: string, ...args: any[]): any {
const maxLength = args[0]
const maxLengthNotProvided = !maxLength
const isShorterThanMaximumLength = value.length < maxLength
if (maxLengthNotProvided || isShorterThanMaximumLength) {
return value
}
const shortenedString = value.substr(0, maxLength - 3)
return `${shortenedString}...`
}
}
app.component.component
<h1>{{ application.name | truncateText:45 }}</h1>
모든 브라우저에서 완벽하게 지원됩니다.
두 가지 다른 방법으로 제 솔루션을 사용해 보세요.
<div class="wrapper">
<p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
<div class="wrapper">
<p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
.wrapper {
padding: 20px;
background: #eaeaea;
max-width: 400px;
margin: 50px auto;
}
.demo-1 {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
.demo-2 {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 150px;
}
글꼴의 너비를 항상 확인하고 평균 문자 픽셀 크기를 취할 수 있습니다.그러면 원하는 글자 수에 곱하기만 하면 됩니다.좀 촌스럽지만 금방 고쳐지는 효과가 있습니다.
75자
최대 너비를 시도해 보았지만 배치가 엉망입니다.
사용하다max-width: 75ch이 너비를 넘어도 엉망이 되지 않는 레이아웃을 만듭니다.
이 코드는 다음과 같이 작동합니다.
.on_table{
table-layout: fixed;
}
.on_tr_td{
border:1px solid grey;
max-width: 20ch;
color: green;
word-break:break-all
}
언급URL : https://stackoverflow.com/questions/26973570/setting-a-max-character-length-in-css
'programing' 카테고리의 다른 글
| npm ERR!노드용 도커 이미지를 만드는 동안 트래커 "idealTree"가 이미 있습니다. (0) | 2023.09.11 |
|---|---|
| Laravel-5 데이터베이스의 선택 상자를 ID 값과 이름 값으로 채우는 방법 (0) | 2023.09.11 |
| 링크된 서버에 대한 "IF EXISTRESS" 테스트가 있습니까? (0) | 2023.09.11 |
| 장고에서 부울 필드의 기본값으로 True를 설정하는 방법은 무엇입니까? (0) | 2023.09.11 |
| Android 내장 메모리에서 비트맵/이미지 저장 및 읽기 (0) | 2023.09.06 |

