Explain Codes LogoExplain Codes Logo

Setting a max character length in CSS

html
responsive-design
css
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 25, 2025
TLDR

¦Speedy solution: CSS can't set a concrete character limit; it primarily controls how the content visually manifests concerning the available space. Inputs in HTML have a maxlength attribute for this specific purpose.

CSS (for divs, not input):

.truncate { max-width: 75ch; // Set width (think of ch as chocolate width of 75 bars!) white-space: nowrap; // anti-wrap defense activated overflow: hidden; // hide your overflowed secrets here text-overflow: ellipsis; // Keep them guessing with an ellipsis... }

HTML (for inputs):

<input type="text" maxlength="10"> // Input field - holdin' it down for just 10 characters!

Building background knowledge

Defining the max character length in CSS isn't about raw numbers. It's about controlling visual boundaries for the readable text, i.e., how it fits in a given space. The ch unit, representing the 0-width character, is an approximate metric for our purpose.

Winning with truncation

Single-line overflow control: Combine white-space, overflow, and text-overflow properties to cut off a lengthy text. The overflow evidence? An ellipsis (...) at the horizon.

Multi-line halting: Use -webkit-line-clamp for multi-line text-cut, a complex technique that might require flexbox and other advanced CSS skills.

Responsive character limits: With media queries, you can adjust the limit based on screen size - keeping the adaptive edge intact.

Customising your game plan

The ch unit - your precision tool

Enter ch unit. Want an approximate width that accommodates, say, around 75 characters? Set max-width: 75ch as your first try, adjusting based on the font in question.

Controlling overflow across device dimensions

Good practice - test your layout on different devices. max-width alone, even when set in px or em, won't promise responsiveness. Media queries are your secret CSS weapon for fluid layouts.

Advanced truncation might need the power of properties like display and flex. But remember, you need to keep the layout's current state as your starting point. Because above all, you can't sacrifice readability.

Considerations while truncating

Remember, you don't want to lose your message while getting rid of the extra. The truncated text needs to speak out loud and clear. So experimentations and adjustments for a better user experience are unavoidable.