Skip to content

How to Truncate Strings Easily with CSS

How to Truncate Strings Easily with CSS

This article was written over 18 months ago and may contain information that is out of date. Some content may be relevant but please refer to the relevant official documentation or available resources for the latest information.

You'll often need to truncate text when working with user interfaces, especially when displaying content within a limited space. CSS provides a straightforward way to handle this scenario, ensuring that long text strings are cut off gracefully without affecting the overall layout.

CSS Truncation Techniques

Single-Line Truncation

If you want to truncate a single line of text, CSS provides a simple solution. The key properties to use here are overflow, white-space, and text-overflow.

.truncate {
white-space: nowrap; /* Prevent the text from wrapping to the next line */
overflow: hidden; /* Ensure content is clipped within the container */
text-overflow: ellipsis; /* Add ellipsis (…) when the text is truncated */
width: 200px; /* Adjust the width as needed */
}

Explanation of properties:

  • white-space: nowrap: This ensures the text stays on a single line, preventing wrapping.
  • overflow: hidden: This hides any content that overflows the container.
  • text-overflow: ellipsis: This adds the ellipsis (…) at the end of the truncated text.

Multi-Line Truncation

While truncating a single line of text is common, sometimes you may want to display multiple lines but still cut off the text when it exceeds a certain number of lines. You can use a combination of CSS properties such as -webkit-line-clamp along with the display and overflow properties.

.multi-line-truncate {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* Limit to 3 lines */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

Live example:

Explanation of properties:

  • display: -webkit-box: This is a legacy flexbox-like display property that works with the -webkit-line-clamp property.
  • -webkit-line-clamp: Specifies the number of lines to show before truncating.
  • -webkit-box-orient: vertical: Ensures the box is laid out vertically for proper multi-line truncation.
  • overflow: hidden: Prevents content overflow.
  • text-overflow: ellipsis: Adds an ellipsis after the truncated content.

Why Use CSS for Text Truncation Over JavaScript Techniques?

While it’s possible to truncate text using JavaScript, CSS is often a better choice for this task for several reasons. Let's explore why CSS-based truncation techniques are generally preferred over JavaScript.

Performance Efficiency

CSS operates directly within the browser's layout engine, meaning it doesn’t require additional processing or event handling as JavaScript does. When using JavaScript to truncate text, the script needs to run on page load (or after DOM manipulation), and sometimes, it needs to listen for events such as window resizing to adjust truncation. This can introduce unnecessary overhead, especially in complex or resource-constrained environments like mobile devices.

CSS, on the other hand, is declarative. Once applied, it allows the browser to handle text rendering without any further execution or processing. This leads to faster load times and a smoother user experience.

Simplicity and Maintainability

CSS solutions are much simpler to implement and maintain than their JavaScript counterparts. All it takes is a few lines of CSS to implement truncation. In contrast, a JavaScript solution would require you to write and maintain a function that manually trims strings, inserts ellipses, and re-adjusts the text whenever the window is resized.

Here's the JavaScript Truncation Example to compare the complexity:

JavaScript Truncation Example:

function truncateText(element, maxLength) {
  const originalText = element.textContent;
  if (originalText.length > maxLength) {
    element.textContent = originalText.substring(0, maxLength) + '...';
  }
}

const element = document.querySelector('.truncate');
truncateText(element, 50);

At the example above, we truncated the text to 50 characters which may be 1 line on large screens and 6 lines on mobile and in that case we will need to add more code to truncate it responsively. As you can see, the CSS solution we used earlier is more concise and readable, whereas the JavaScript version is more verbose and requires managing the string length manually.

Responsiveness Without Extra Code

With CSS, truncation can adapt automatically to different screen sizes and layouts. You can use relative units (like percentages or vw/vh), media queries, or flexbox/grid properties to ensure the text truncates appropriately in various contexts.

If you were using JavaScript, you’d need to write additional logic to detect changes in the viewport size and update the truncation manually. This would likely involve adding event listeners for window resize events, which can degrade performance and lead to more complex code.

CSS Example for Responsive Truncation:

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 50%; /* Automatically adjusts based on screen size */
}

To achieve this in JavaScript, you’d need to add more code to handle the width adjustments dynamically, making it more complex to maintain and troubleshoot.

Separation of Concerns

CSS handles the presentation layer of your website, while JavaScript should focus on dynamic functionality or data manipulation. By keeping truncation logic within your CSS, you're adhering to the principle of separation of concerns, where each layer of your web application has a clear, well-defined role.

Using JavaScript for visual tasks like truncation mixes these concerns, making your codebase harder to maintain, debug, and scale. CSS is purpose-built for layout and visual control, and truncation is naturally a part of that domain.

Browser Support and Cross-Browser Consistency

Modern CSS properties like text-overflow and -webkit-line-clamp are widely supported across all major browsers. This means that CSS solutions for truncation are generally consistent and reliable. JavaScript solutions, on the other hand, may behave differently depending on the browser environment and require additional testing and handling for cross-browser compatibility.

While older browsers may not support specific CSS truncation techniques (e.g., multi-line truncation), fallback options (like single-line truncation) can be easily managed through CSS alone. With JavaScript, more complex logic might be required to handle such situations.

Reduced Risk of Layout Shifting

JavaScript-based text truncation risks causing layout shifting, especially during initial page loads or window resizes. The browser may need to recalculate the layout multiple times, leading to content flashing or jumpy behavior as text truncation is applied.

CSS-based truncation is applied as part of the browser’s natural rendering flow, eliminating this risk and ensuring a smoother experience for the user.

Conclusion

CSS is the optimal solution for truncating text in most cases due to its simplicity, efficiency, and responsiveness. It leverages the power of the browser’s rendering engine, avoids the overhead of JavaScript, and keeps your code clean and maintainable. While JavaScript truncation has its use cases, CSS should always be your go-to solution for truncating strings, especially in static or predictable layouts. If you like this post, check out the other CSS posts on our blog!

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

You might also like

The CSS / Utility hybrid approach with Tailwind v4 cover image

The CSS / Utility hybrid approach with Tailwind v4

Just recently, the progress on the next major version of Tailwind CSS was open-sourced, along with a preview post. This is very exciting news to me, and I love the direction they’ve taken with this release. Tailwind can be a pretty polarizing topic among developers, but I believe that we can find some common ground and live in harmony. In this post, we’ll look at how the CSS + Tailwind hybrid approach is getting an upgrade in v4 and some of the patterns that we can take advantage of to provide a stellar styling experience on our websites. The hybrid approach It doesn’t matter what your personal take on Tailwind is, the fact is utility classes are an incredibly useful pattern for styling websites with CSS. I’m not sold on the hard-line, all-or-nothing approach that Tailwind has always recommended. Having a class string that extends way off the screen on an ultra-wide monitor is not pretty. Combining traditional CSS classes with utility classes helps cut down on the styling noise in your markup and provides some advantages when applied correctly. This post will cover some useful patterns and best practices for using CSS and Tailwind in harmony Tailwind going “CSS-native” In the v4 introduction post, they state A major goal of Tailwind CSS v4.0 is making the framework feel CSS-native, and less like a JavaScript library. I love that they are heading in this direction, and I’m imagining Tailwind as the toolkit for styling websites with CSS. It is going to replace the plethora of tools from the past and provide support for all the modern niceties like: * Importing CSS files with @import * Vendor prefixing _(no more autoprefixr)_ * Improved browser support for modern features like CSS nesting and media query ranges. This means less worry for us as developers. We can write our code and build our sites using the modern features that the platform provides without sweating all the other details and edge cases. The talented folks at Tailwind and the open-source community have our backs. Tailwind v4 CSS configuration The biggest step in the “CSS-native” direction and the feature that I’m most excited about is the CSS configuration. This is great for embracing CSS and Tailwind as one instead of two factions at battle. If you’ve been using Tailwind exclusively for a long time like I have, you might be out of touch with all the great features and tools that CSS provides out of the box now. This is a great opportunity to get back to learning and using the platform. In Tailwind v4 we do our configuration and theming with CSS variables. To get an idea of what this looks like check out the default theme on GitHub. In our configuration we can override any values from the default theme or extend it with new values. ` All the values from the theme are exposed as CSS variables. We can reference them in our CSS files or directly in our utility classes. ` ` Best practices for combining CSS with utility classes I can understand why Tailwind recommends using strictly utility classes. It’s easy to shoot yourself in the foot and run into the issues that utility classes set out to solve in the first place. I believe if you follow some general guidelines you can safely have the best of both worlds. Create focused/specialized classes CSS tends to get messy when we use classes that are overly specific with styles that apply to just one or a small number of use cases. Take a calendar where the days are custom checkboxes. You might have some pretty specialized styles for this bit of UI. ` Notice that we just add some specific styles that apply to this use case. This gives us the flexibility to keep composing our styles with utility classes. Some things are better left to utilities The best way to avoid wandering too far off the path of enlightenment is to stick with utility classes for certain (most?) things. Spacing and layouting are examples of things that are probably best left to utility classes. These typically vary all across a page, and encoding them in a class will make it a lot less flexible. A code smell to look out for: If you have abstracted something to a class and you end up overriding certain aspects of its styles in different places. Those styles should probably be utility classes. Classes as components Tailwind has always recommended using a component system for your UI components so that your utility classes are all defined in a single place. You don’t want to have to edit 50 different files to make a change to the style of your buttons across your website. I’ve found that defining things that might be simple “components” like buttons, badges, links, etc as classes works just as well in most cases. You can use Tailwind CSS with the @apply directive or traditional class definitions for this: ` You can even bring the BEM naming convention back to compose variants on top of base component styles. (or name them however you’d like!) ` Now we can easily define badges in our markup: ` Modern CSS and other interesting utility hybrid patterns I think a lot of us are realizing that modern CSS is pretty great. There are a ton of awesome new features gaining support across major browsers, like CSS nesting, container queries, and more! More and more people are also coming around to the utility of utility classes. If you want to dive deeper and see other interesting approaches and patterns when combining modern CSS with utility classes, check out the post: Modern CSS patterns in Campfire. Summary I’m looking forward to the Tailwind CSS configuration and other awesome updates coming in v4. Using Tailwind doesn’t have to be a one-size-fits-all approach. If you want to write some CSS, I say go for it! Hopefully, some of the points in this post will lead to success if you decide to do so....

Understanding the Difference Between `:focus` and `:focus-visible` in CSS cover image

Understanding the Difference Between `:focus` and `:focus-visible` in CSS

Understanding the Difference Between :focus and :focus-visible in CSS I have learned my fair share about the importance of keyboard accessibility, so I know that visual indication of the focused element is very important. But the well-known :focus pseudo-class is not always the best fit for this job. That's where :focus-visible comes in. Let's look at the differences between these two pseudo-classes and explore the best practices for using them effectively. What is the :focus Pseudo-Class? The :focus pseudo-class is a CSS selector that applies styles to any element that receives focus, regardless of how that focus was triggered. This includes focus events from keyboard navigation, mouse clicks, and touch interactions. Example Usage of :focus ` In this example, the button will display a blue outline whenever it is focused, whether the user clicks on it with a mouse, taps it on a touchscreen, or navigates to it using the keyboard. What is the :focus-visible Pseudo-Class? The :focus-visible pseudo-class is more specialized. It only applies styles to an element when the browser determines that the focus should be visible. This typically occurs when the user navigates via the keyboard or assistive technologies rather than through mouse or touch input. Example Usage of :focus-visible ` Here, the button will only show a blue outline when focused through keyboard navigation or another input method that usually requires visible focus indicators. Key Differences Between :focus and :focus-visible :focus - Behavior: Applies to any element that receives focus, regardless of the input method. - Use Cases: Ensures that all interactions with the element are visually indicated, whether by mouse, keyboard, or touch. :focus-visible - Behavior: Applies styles only when the focus should be visible, such as using a keyboard or assistive technology. - Use Cases: Ideal for scenarios where you want to provide focus indicators only to keyboard and assistive technology users while avoiding unnecessary outlines for mouse and touch users, typically required by design. Accessibility Implications :focus - Pros: - Guarantees that all users can see when an element is focused, which is critical for accessibility. - Cons: - Can lead to a suboptimal experience for mouse users, as focus styles may appear unnecessarily during mouse interactions. :focus-visible - Pros: - Enhances user experience by showing focus indicators only when necessary, thus keeping the interface clean for mouse and touch users. - Tailors the experience for keyboard and assistive technology users, providing them with clear visual cues. - Cons: - Additional considerations may be required to ensure that focus indicators are not accidentally omitted, especially in older browsers that do not support :focus-visible. - There may be cases where you want to show focus indicators for all users, regardless of input method. Best Practices for Using :focus and :focus-visible To achieve the best accessibility and user experience, combining both :focus and :focus-visible in your CSS is often a good idea. Combining :focus and :focus-visible ` Here is a Stackblitz example of what such styling could look like for you to try out and play with. Additional Tips - Test with Keyboard and Assistive Technology: Ensure that your web application is navigable using a keyboard (Tab, Shift + Tab, etc.) and that focus indicators are visible for those who rely on them. It's never a bad idea to include accessibility testing in your e2e testing suite. - Provide Clear Focus Indicators: Make sure that focus indicators are prominent and easy to see. A subtle or hard-to-spot focus indicator can severely impact accessibility for users who rely on keyboard navigation. Conclusion The :focus-visible pseudo-class offers a more refined way to manage focus indicators, improving accessibility and user experience, particularly for keyboard and assistive technology users. By understanding the differences between :focus and :focus-visible, and applying best practices in your CSS, you can create more accessible and user-friendly web applications. Remember, accessibility should never be an afterthought. By thoughtfully applying focus styles, you ensure that all users, regardless of how they interact with your site, can easily navigate and interact....

Export Your Data from Universal Analytics before you lose it cover image

Export Your Data from Universal Analytics before you lose it

Introduction In 2023, Google announced the retirement of Universal Analytics and told everyone to migrate to Google Analytics 4, commonly known as GA4. Google Analytics has long been a staple for businesses and website owners seeking insights into their audience and performance metrics. However, with the introduction of Google Analytics 4, there comes a pivotal moment for users of the older Universal Analytics (UA) platform. Difference between UA and GA4 What data will you lose? You will lose ALL of the historical data! By July 1, 2024, Google will delete all UA data, and you will no longer have access to it after that. Also, Universal Analytics will no longer track new conversions, affecting ad campaign performance that relies on these conversions for Smart Bidding. Audience lists from Universal Analytics will also disappear, potentially impacting media activation and performance. API requests tied to Universal Analytics properties will fail, preventing data deletion requests and causing Looker Studio to stop displaying Universal Analytics data. Additionally, Attribution Projects (beta) in Google Analytics will be deleted. How to Export Your Data There are multiple ways to export your data from Google Analytics, such as using the Google Analytics add-on for Google Sheets or using BigQuery integration to export historical data from your Universal Analytics 360 property. This article will discuss the easiest way to export your data using the Google Analytics add-on from Google Workspace Marketplace. From “Extensions” > “Google Analytics” > “Create new report” The Google Analytics extension will display a Wizard that requires the following steps: * Set a name for your report * Then, you select the Google Analytics account * Then, the property you want to export * Also, there are some optional configuration that helps you filter the data you want to export Then click on “Create Report,” and it will export the report for you Here is an example of the template https://docs.google.com/spreadsheets/d/1zXEBEQQk6TPeGb7-Wm2J0uM0q0XnTdJqrfikCTmYs8c/copy Running the Report After setting up the report template with the necessary configurations, users can run the report to extract their UA data into Google Sheets. Depending on the size of the dataset, the report may take some time to generate, especially for larger datasets spanning multiple years. In such cases, splitting the data into smaller chunks may be necessary to ensure efficient processing. Conclusion As Google transitions from Universal Analytics to Google Analytics 4, businesses and website owners must proactively preserve their valuable historical data. With the impending deletion of all Universal Analytics data by July 1, 2024, failing to export your data in time could result in significant data loss, affecting ad campaign performance and analytics capabilities. By following the outlined methods to export data using tools like the Google Analytics add-on for Google Sheets, you can ensure that your historical data is safely archived and accessible for future analysis....

Making AI Deliver: From Pilots to Measurable Business Impact cover image

Making AI Deliver: From Pilots to Measurable Business Impact

A lot of organizations have experimented with AI, but far fewer are seeing real business results. At the Leadership Exchange, this panel focused on what it actually takes to move beyond experimentation and turn AI into measurable ROI. Over the past few years, many organizations have experimented with AI, but the challenge today is translating experimentation into measurable business value. Moderated by Tracy Lee, CEO at This Dot Labs, panelists featured Dorren Schmitt, Vice President IT Strategy & Innovation at Allen Media Group, Greg Geodakyan, CTO at Client Command, and Elliott Fouts, CAIO & CTO at This Dot Labs. Panelists discussed how companies are moving from early AI experiments to initiatives that deliver real results. They began by examining how experimentation has evolved over the past year. While many organizations did not fully utilize AI experimentation budgets in 2025, 2026 is showing a shift toward more intentional investment. Structured budgets and clearly defined frameworks are enabling companies to explore AI strategically and identify initiatives with high potential impact. The conversation then turned to alignment and ROI. Panelists highlighted the importance of connecting AI projects to corporate strategy and leadership priorities. Ensuring that AI initiatives translate into operational efficiency, productivity gains, and measurable business impact is essential. Companies that successfully align AI efforts with organizational goals are better equipped to demonstrate tangible outcomes from their investments. Moving from pilots and proofs of concept to production was another major focus. Governance, prioritization, and workflow integration were cited as essential for scaling AI initiatives. One panelist shared that out of nine proofs of concept, eight successfully launched, resulting in improvements in quality and operational efficiency. Panelists also explored the future of AI within organizations, including the potential for agentic workflows and reduced human-in-the-loop processes. New capabilities are emerging that extend beyond coding tasks, reshaping how teams collaborate and how work is structured across departments. Key Takeaways - Structured experimentation and defined budgets allow organizations to explore AI strategically and safely. - Alignment with business priorities is essential for translating AI capabilities into measurable outcomes. - Governance and workflow integration are critical to moving AI initiatives from pilot stages to production deployment. Successfully leveraging AI requires a balance between experimentation, strategic alignment, and operational discipline. Organizations that approach AI as a structured, measurable initiative can capture meaningful results and unlock new opportunities for innovation. Curious how your organization can move from AI experimentation to real impact? Let’s talk. Reach out to continue the conversation or join us at an upcoming Leadership Exchange. Tracy can be reached at tlee@thisdot.co....

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co