CSS
CSS: How to Keep Text Within a Bordered Container
When designing a webpage, it’s common to place text inside a bordered container—like a card, box, or alert. But if not styled correctly, the text may overflow, break the layout, or touch the borders, making it hard to read.
In this blog post, you’ll learn:
- ✅ How to place text inside a bordered box
- ✅ How to use CSS properties to keep the text contained
- ✅ How to prevent overflow issues
- 🧪 Practical examples with borders, padding, and overflow control
✅ 1. Basic Bordered Container with Text
Let’s start with a clean, simple container.
✅ HTML:
<div class="text-container">
This is some text inside a bordered container. It stays neatly inside the box.
</div>
✅ CSS:
.text-container {
border: 2px solid #333;
padding: 16px;
width: 300px;
font-family: Arial, sans-serif;
}
✅ Padding creates space between the text and the border, keeping it readable.
🚫 2. Prevent Text Overflow (Long Words or URLs)
Sometimes, long text like URLs or unbroken strings can overflow the box.
✅ Fix It with:
.text-container {
word-wrap: break-word;
overflow-wrap: break-word;
}
✅ Example:
<div class="text-container">
ThisIsAnExtremelyLongUnbrokenWordThatWouldNormallyBreakTheBoxLayoutButNowWrapsCorrectly.
</div>
🧠 This makes the container wrap long words instead of letting them spill out.
🧪 3. Scrollable Overflow (Optional)
If you want the container to scroll when there’s too much text:
.scroll-box {
width: 300px;
height: 100px;
border: 1px solid #999;
padding: 10px;
overflow: auto;
}
<div class="scroll-box">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...
</div>
✅ This ensures content stays within the border without breaking the layout.
🧠 Summary of CSS Properties
Property | Purpose |
---|---|
border | Creates the visible container |
padding | Adds space between text and border |
overflow-wrap | Prevents long words from overflowing |
overflow | Controls scrolling or clipping of overflow text |
width / height | Defines box dimensions |
🧠 Best Practices
- ✔️ Always use
padding
to avoid text hugging the border - ✔️ Use
overflow-wrap: break-word
for long strings - ✔️ Consider
max-width
orwidth
for consistency - ✔️ Use responsive units (
em
,%
,rem
) for fluid layouts
🏁 Final Thoughts
Keeping text within a bordered container is essential for clean, readable design. With just a few CSS properties like padding
, border
, and overflow-wrap
, you can ensure your text stays tidy, accessible, and visually appealing—regardless of screen size or content length.