Truncate Text with CSS Overflow

Beginner

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

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.