Home > Web Front-end > JS Tutorial > How to Elegantly Truncate Text in H2 Tags with Ellipsis?

How to Elegantly Truncate Text in H2 Tags with Ellipsis?

Patricia Arquette
Release: 2024-10-30 12:51:27
Original
422 people have browsed it

How to Elegantly Truncate Text in H2 Tags with Ellipsis?

Truncating Text in HTML Tags Using Ellipsis

In a world of responsive web design, it's common to encounter situations where content may exceed the available width of an element, resulting in undesired text wrapping or breakage. For headings (h2) with dynamic text lengths, this can present an aesthetic challenge.

Problem:
How can you elegantly truncate the content within an h2 tag and add an ellipsis (...) when the text exceeds the available width of the screen or container?

Solution:
Fortunately, modern web browsers provide a simple and cross-browser solution using CSS. By adding the following CSS class to the h2 tags, you can achieve the desired effect:

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

This CSS class applies the following settings:

  • white-space: nowrap prevents the text from wrapping to a new line.
  • overflow: hidden hides any content that exceeds the available width.
  • text-overflow: ellipsis and -o-text-overflow: ellipsis (for Opera) display an ellipsis (...) at the end of the truncated text.

Using this CSS class, the h2 tag will gracefully truncate its content and add an ellipsis when it becomes too wide for its container. Note that this solution is valid for all major browsers as of writing, with the exception of Firefox 6.0. For support in earlier versions of Firefox, consider the solution provided in the linked question mentioned in the answer.

The above is the detailed content of How to Elegantly Truncate Text in H2 Tags with 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