Truncate Text with CSS Overflow

CSSCSSBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will dive into the world of CSS programming and learn how to truncate text that exceeds one line's width. By using the combination of overflow, white-space, and text-overflow properties, we will be able to display an ellipsis at the end of the truncated text. Through this lab, we will gain a deeper understanding of how to optimize the display of text on websites.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/BasicStylingGroup(["`Basic Styling`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/BasicStylingGroup -.-> css/text_styling("`Text Styling`") css/CoreLayoutGroup -.-> css/width_and_height("`Width and Height`") subgraph Lab Skills css/selectors -.-> lab-35253{{"`Truncate Text with CSS Overflow`"}} css/text_styling -.-> lab-35253{{"`Truncate Text with CSS Overflow`"}} css/width_and_height -.-> lab-35253{{"`Truncate Text with CSS Overflow`"}} end

Truncate Text

index.html and style.css have already been provided in the VM.

To truncate text that is longer than one line and add an ellipsis at the end, use the following CSS properties:

  • overflow: hidden to prevent text from overflowing its dimensions
  • white-space: nowrap to prevent text from exceeding one line in height
  • text-overflow: ellipsis to add an ellipsis if text exceeds its dimensions
  • Specify a fixed width for the element to know when to display an ellipsis

Note that this method only works for single line elements. For example:

<p class="truncate-text">If I exceed one line's width, I will be truncated.</p>
.truncate-text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  width: 200px;
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Truncate Text lab. You can practice more labs in LabEx to improve your skills.

Other CSS Tutorials you may like