I recently cracked the code on a CSS template that flawlessly wraps long text into any number of lines without causing overflow. It's a game-changer for clean, responsive layouts, and I'm jotting it down here for future reference. This solution ensures that text stays contained and visually appealing, regardless of the container size or content length.
Refer to this sandbox link
Demo
Let'see
<div class="container">
<div class="card">
<h4>A Big Paragraph</h4>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Impedit non
repellendus error quod sunt maiores voluptatum rerum illum, sit neque?
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Temporibus
ipsa tenetur nihil placeat soluta rerum fugiat, sequi saepe dolorem
iste ut beatae quos! Maxime repudiandae dolor labore nulla! Modi
adipisci est ex quaerat veritatis obcaecati illo unde nihil delectus.
</p>
</div>
<div class="card">
<h4>A long word without any space</h4>
<p>
jjjjjjjjjjjjjjjjdjdjdjdndndndndndjdjsaanansnsns@djejr12243nnfnfnfngn@nfgfgjrmrnn4jfmfnm$mbmbbjbmnfgnvmfmfmfm#kvkfmfmfmfm
</p>
</div>
</div>
So the CSS for the card and container
.container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.card {
box-shadow: 0 0px 5px rgba(0, 0, 0, 0.2);
border-radius: 5px;
padding: 0 20px;
width: 40%;
}
It looks like
See how the long paragraph is growing in height. And our long word is going out of the card, which is disturbing our whole grid.
How to fix it? 🤔
Add this 🥷 Ninja Technique to p
tag
p {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
text-overflow: ellipsis;
overflow-wrap: anywhere;
}
-webkit-line-clamp
, you can modify this value to adjust your wrapping to limit the number of lines shown. Any text that goes beyond this limit will be hidden. In my case, it goes up to line 2
overflow-wrap: anywhere;
this we are using to handle long, big strings or words, like in our case. This property allows the browser to break words at any point to prevent overflow.
Boom see result
Give it a try.
Follow me for more tips like this 🙌
Top comments (0)