惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

Ahmad Shadeed

Better fluid sizing with round() Use Cases for Field Sizing The Basics of Anchor Positioning Item Flow CSS Relative Colors Balancing Text In CSS Should masonry be part of CSS grid? CSS display contents CSS Grid Areas CSS Cap Unit An Interactive Guide to CSS Container Queries CSS :has() Interactive Guide CSS Nesting UX in DevTools CSS Nesting Future CSS: State Container Queries Rebuilding a comment component with modern CSS Conditional CSS with :has and :nth-last-child CSS Text balancing with text-wrap:balance CSS Masking Do we need CSS flex-wrap detection? My CSS Wishlist Conditional CSS CSS Style Queries Inside the mind of a frontend developer: Article layout Inside the mind of a frontend developer: Hero section CSS container queries are finally here The CSS behind Figma First Look At The CSS object-view-box Property Learn CSS Subgrid CSS :has Parent Selector Aligning Content In Different Wrappers Flexbox Dynamic Line Separator Hello, CSS Cascade Layers Building UI Components With SVG and CSS A Deep CSS Dive Into Radial And Conic Gradients Defensive CSS Building Real-life Components: Facebook Messenger Conditional Border Radius In CSS CSS Container Query Units Less Absolute Positioning With Modern CSS Aligning a Button Label Vertically Comparing Design Mockups To Code Result Using HSL Colors In CSS Custom Scrollbars In CSS Let CSS Container Queries For Designers The State of CSS Cross-Browser Development Overflow Issues In CSS Inspect Element As A Way To Increase Your Curiosity Handling Text Over Images in CSS Digging Into CSS Logical Properties Clipping Scrollable Areas On The inline-start Side Understanding Clip Path in CSS The Art of Building Real-life Components CSS Scroll Snap A Deep Dive Into CSS Grid minmax() CSS Variables 101 Finding The Root Cause of a CSS Bug Learn CSS centering How to detect browser support for Flexbox Gap CSS Mistakes While On Autopilot Digging Into the Flex Property Understanding CSS Multiple Backgrounds Aligning Logo Images in CSS Grid for layout, Flexbox for components Colors in CSS Thinking About The In-between Design Cases min(), max(), and clamp() CSS Functions Image Techniques On The Web Everything About Auto in CSS Learn Box Alignment Let Learn CSS Positioning Intrinsic Sizing In CSS CSS Grid Template Areas In Action Hiding Elements On The Web Creating a Variable Color Font From Scratch Building a Football Ticket With CSS and SVG Blending Modes in CSS CSS Variables With Inline Styles Implementing Dark Mode For My Website Rebuilding Apple Music Header in HTML & CSS Accessible Checkbox Layout Flickering On Browser Resize Enhancing The Clickable Area Size Custom Underlines with SVG Part 3: The Process of Implementing A UI Design From Scratch Part 2: The Process of Implementing A UI Design From Scratch Building An Old Nav Design CSS Flexbox: 5 Real World Use Cases I Used CSS Inline Flex For The First Time The Process of Implementing A UI Design From Scratch Common CSS Issues For Front-End Projects Handling Long and Unexpected Content in CSS How to Build Web Form Layouts With CSS Grid Grid Layout Ah-ha Moment Enhancing Our Components with CSS :empty Building Resizeable Components with Relative CSS Units CSS Writing Mode The Journey of Learning Front End Web Development on a Daily Basis
Handling Short And Long Content In CSS
Ahmad Shadeed · 2020-12-16 · via Ahmad Shadeed

The Layout Maestro

I spent years teaching CSS layout on this blog. I put everything I know into The Layout Maestro course: 70+ lessons and 150+ interactive examples that teach you how to think CSS layouts, not just memorize syntax.

Get the course

When you build a layout in CSS, it’s important to account for and test short and long text content. Having a clear idea of what to do when the text varies in length can prevent a lot of unwanted issues.

There are many situations where adding or removing one word can change how a design looks, or even worse, it can break it and make it inaccessible. In my early days of learning CSS, I underestimated what adding or removing a word can do. In this article, I will go through the different techniques that you can use right away to handle different text lengths in CSS.

The problem

Before going into the techniques to handle text content, let me shed the light on the problem first. Let’s suppose that we have a vertical navigation.

Names length can vary, especially if you are working on a multilingual website. In the example above, the name is wrapped into a second line as it becomes longer. Here are some questions:

  • Should we truncate the text?
  • Should we wrap into multiple lines? If yes, what’s the maximum number of lines to wrap?

That’s the case with more words than expected, but what happens when a word is too long? By default, it will overflow its container.

As a front-end developer, it’s important to decide on what should happen in such cases. Luckily, there are some CSS properties that were designed just for solving such problems.

Adding on that, the problem is not only about long content, but also short content can break a UI, or make it look weird, at least. See the example below:

The button with the text “ok” is very small in width. I’m not saying that this is a fatal problem, but it can make the button look weak or hard to be noticed.

What we should do in such a case? Maybe set a min-width on the button? That can provide a safe width regardless of the content length.

As you just read, it’s not about the long content. Also, short content can cause problems. By using some CSS techniques, we can at least reduce the issues of long or short content.

Now that you have an idea about the problems, let’s dig into the CSS techniques that provide a solution for dealing with long content.

Overflow wrap

The overflow-wrap property guides the browser into setting a break in case a word can’t fit its container.

.card {
  overflow-wrap: break-word;
}

Hyphens

A CSS property that lets the bowser decide on how words should be hyphenated when text content wraps across multiple lines. The hyphenation can either be done manually by inserting an HTML symbol that guides the browser if it needs to hyphenate a word.

.element {
  hyphens: auto;
}

Though, it’s important to keep in mind that hyphens: auto will hyphenate any word that can’t fit in a line. What does that mean? See the below figure.

Notice how the browser hyphenated a word while it can be simply moved to the next line. When using hyphens: auto, it doesn’t matter if a word can’t fit in its container or not.

Text truncation

Truncation means adding dots at the end of a sentence to give an indication that there is more text content.

There is no text-truncation property or something, but it’s a mix of some CSS properties that do the job for us.

.element {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Multiple line text truncation

If you want multiple line truncation, you should use line-clamp property.

.element {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

For this technique to work, display: -webkit-box must be used. The -webkit-line-clamp specifies the maximum number of lines for the truncation to work.

The downside to this technique is that it can easily fail if you want to add padding for the element. When you add padding, this will result in showing a part of the next line, which is supposed to be truncated. See the figure below:

Horizontal scrolling

Sometimes, it’s not always practical to break or hyphenate a word. For example, a javascript code might become hard to read when a long word is broken into a new line. In such a case, allowing horizontal scrolling will make the reading experience better.

.code {
  overflow-x: auto;
}

Padding

In some cases, you might forget to add padding until you notice a visual issue. Consider the following:

We have a list of checkboxes, and one of them is very close to its sibling item. The reason that this happened is that there is no gutter on the grid. This is a real-life example from Techcrunch website.

Short content

I know that this might not be that common for you, but it’s an important thing to consider when designing and building a UI.

Setting a minimum width

Let’s get back to the example that I showed you at the beginning of the article. How can we enhance this and make the button look better?

We can solve this by simply adding a min-width to the button. That way, it won’t go below that width.

Now that you have an idea about the problem and its solutions, let’s explore some use cases and examples from around the web.

Use cases and examples

Profile card

This is a common example of long content. It’s hard to predict the length of a name. How we should deal with it?

/* Solution 1 */
.card__title {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

/* Solution 2 */
.card__title {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

You can either truncate the text with a single line or do the truncation only when the text is two lines long.

When dealing with a multilingual layout, the content length will change. Consider the following example:

The navigation item “About” is larger in LTR (left-to-right) compared to RTL (right-to-left). In RTL, the item looks too small. Having a small clickable area is not good for UX. What we can do? In such a case, it will be a good idea to set a minimum width for the navigation item.

.nav__item {
  min-width: 50px;
}

For more details about the difference between words, I wrote about this in detail in my RTL styling 101 guide.

Article content

Having a long word or a link is common, especially on mobile. Consider the following:

We have a long word that is overflowing its container and causing horizontal scrolling. As you learned, you can solve this by either using overflow-wrap or hyphens.

.article-content p {
  overflow-wrap: break-word;
}

Shopping cart

A product name can vary from one word to multiple lines. In this example, the product name is too close to the delete button as a result of not adding enough spacing between them.

The solution can be done by either adding padding or margin. It’s up to you and the context, but for simplicity reason, I will show you the margin solution.

.product__name {
  margin-right: 1rem;
}

Flexbox and long content

There is a behavior that happens with flexbox and long content that causes an element to overflow its parent. Consider the following example:

<div class="user">
  <div class="user__meta">
    <h3 class="user__name">Ahmad Shadeed</h3>
  </div>
  <button class="btn">Follow</button>
</div>
.user {
  display: flex;
  align-items: flex-start;
}

.user__name {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

However, when the content is long, this won’t work. The text will overflow its parent.

The reason is that flex items won’t shrink below their minimum content size. To solve this, we need to set min-width: 0 on the flex item .user__meta.

.user__meta {
  /* other styles */
  min-width: 0;
}

For me details, you can read about this in the Min and Max Width/Height in CSS article on my blog.

Conclusion

I hope that you learned about the different techniques to deal with short and long content in CSS. I enjoyed working on this article as it refreshed some little details, and will be a good reminder for me in some upcoming projects.

Other resources

I wrote an ebook

I’m excited to let you know that I wrote an ebook about Debugging CSS.

If you’re interested, head over to debuggingcss.com for a free preview.