Home > Web Front-end > JS Tutorial > body text

How Can I Truncate Overly Long HTML Headers with an Ellipsis?

Susan Sarandon
Release: 2024-11-01 08:08:02
Original
238 people have browsed it

How Can I Truncate Overly Long HTML Headers with an Ellipsis?

Elegant Solution for Truncating Excessively Wide HTML Headers

In a dynamic webpage with adjustable layout, it's common to encounter headlines (h2) of varying lengths. When these headlines exceed the browser window width, they typically break into multiple lines. To avoid this undesirable behavior, let's explore a sophisticated solution to truncate the headline text and insert an ellipsis (...) if it would overflow into multiple lines.

Using the power of CSS, we can devise a cross-browser solution that achieves this truncation effortlessly. Here's the code:

<code class="css">.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}</code>
Copy after login

This code defines a CSS class named "ellipsis" with specific properties:

  • white-space: nowrap;: Prevents the text from wrapping onto multiple lines.
  • overflow: hidden;: Hides any text that exceeds the element's width.
  • text-overflow: ellipsis; and -o-text-overflow: ellipsis;: Inserts an ellipsis (...) at the end of the truncated text for most modern browsers and Opera, respectively.

By applying this CSS class to your problematic h2 elements, you can ensure that they will be truncated to a single line and display an ellipsis if the text overflows. This solution is both elegant and compatible with all major browsers except Firefox 6.0. For earlier versions of Firefox, you may refer to other resources that address multiline text wrapping.

The above is the detailed content of How Can I Truncate Overly Long HTML Headers with an Ellipsis?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!