Een maximale tekenlengte instellen in CSS

Ik maak een responsieve website voor school en mijn vraag is:

Hoe stel ik een maximale tekenlengte in van de zinnen (met CSS) op mijn website (zoals 75 tekens) dat als ik een heel groot scherm heb, de zinnen niet verder gaan dan 75 tekens.

Ik heb een maximale breedte geprobeerd, maar dat verpest mijn lay-out. Ik gebruik flexbox en mediaquery’s om het responsief te maken.


Antwoord 1, autoriteit 100%

Je zou altijd een truncate-methode kunnen gebruiken door een max-widthin te stellen en ellipsisals volgt in te stellen

p {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

Een voorbeeld:

.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>

Antwoord 2, autoriteit 44%

Er is een CSS ‘lengtewaarde’ van ch.

Van MDN

Deze eenheid vertegenwoordigt de breedte, of beter gezegd de voormaat,
van de glyph ‘0’ (nul, het Unicode-teken U+0030) in de element’s
lettertype.

Dit kan een benadering zijn van wat u zoekt.

p {
  overflow: hidden;
  max-width: 75ch;
}
<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>

Antwoord 3, autoriteit 17%

Probeer dit om tekens af te kappen nadat u deze op max-width hebt ingesteld. Ik heb in dit geval 75ch gebruikt

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>

Antwoord 4, autoriteit 7%

voorbeeldcode:

.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>
    

Antwoord 5, autoriteit 7%

Met Chrome kunt u het aantal weergegeven regels instellen met “-webkit-line-clamp” :

    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;  /* Number of lines displayed before it truncate */
     overflow: hidden;

Dus voor mij is het om in een extensie te gebruiken, dus het is perfect, meer informatie hier: https://medium.com/mofed/css-line-clamp-the-good-the-bad-and-the-straight-up -gebroken-865413f16e5


Antwoord 6

Dat kan niet met CSS, daar moet je Javascript voor gebruiken. Hoewel je de breedte van de p kunt instellen op maximaal 30 tekens, zullen de volgende letters automatisch naar beneden komen, maar ook dit zal niet zo nauwkeurig zijn en zal variëren als de tekens in hoofdletters zijn.


Antwoord 7

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

RESULTAAT

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi
ligula, dapibus een volutpat sit amet, mattis et…

Jsfiddle


Antwoord 8

Dit bericht is voor een CSS-oplossing, maar het bericht is vrij oud, dus voor het geval anderen hierover struikelen en een modern JS-framework zoals Angular 4+ gebruiken, is er een eenvoudige manier om dit te doen via Angular Pipes zonder te hoeven rommelen met CSS.

Er zijn waarschijnlijk ook “React” of “Vue” manieren om dit te doen. Dit is alleen maar om te laten zien hoe het binnen een kader kan worden gedaan.

truncate-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.html

<h1>{{ application.name | truncateText:45 }}</h1>

Antwoord 9

Modern CSS-rasterantwoord

Bekijk de volledig werkende code op CodePen. Gezien de volgende HTML:

<div class="container">
    <p>Several paragraphs of text...</p>
</div>

Je kunt CSS Grid gebruiken om drie kolommen te maken en de container vertellen dat de middelste kolom die onze alinea bevat een maximale breedte van 70 tekens mag gebruiken.

.container
{
  display: grid;
  grid-template-columns: 1fr, 70ch 1fr;
}
p {
  grid-column: 2 / 3;
}

Zo ziet het eruit (afrekenen CodePenvoor een volledig werkend voorbeeld):

Hier is nog een voorbeeld waarbij u minmax kunt gebruiken om een reeks waarden in te stellen. Op kleine schermen wordt de breedte ingesteld op 50 tekens breed en op grote schermen 70 tekens breed.

.container
{
  display: grid;
  grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}
p {
  grid-column: 2 / 3;
}

Antwoord 10

Pure CSS-oplossing voor het afkappen van tekens met meerdere regels

Ik had een soortgelijk probleem en vond deze uitstekende alleen-css-oplossing van Hackingui.com. U kunt het artikel lezen voor informatie, maar hieronder vindt u de hoofdcode.

Ik heb het getest en het werkt perfect. Hopelijk vindt iemand het nuttig voordat hij kiest voor JS- of server-side-opties

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

Antwoord 11

Probeer mijn oplossing op twee verschillende manieren.

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

Antwoord 12

U kunt altijd kijken hoe breed uw lettertype is en de gemiddelde pixelgrootte van het personage neemt. Vermenig dan gewoon dat door het aantal gewenste tekens. Het is een beetje kleverig, maar het werkt als een snelle oplossing.

Other episodes