In web design, it’s common to place text inside a bordered container to emphasize content, organize layouts, or improve readability. However, if not styled properly, the text can overflow, wrap awkwardly, or clash with the border edges.
This blog post will guide you step-by-step on how to keep text neatly inside a bordered container using CSS.
β Basic Example: Text Inside a Bordered Container
Letβs start with a simple container and see how to keep the text inside properly.
π§Ύ HTML:
<div class="text-box">
This is a sample text inside a bordered container.
</div>
π¨ CSS:
.text-box {
border: 2px solid #444;
padding: 15px;
width: 300px;
font-family: Arial, sans-serif;
}
π Whatβs Happening Here:
border
: Draws the box around the text.padding
: Adds space between the text and the border so it doesn’t touch the edges.width
: Controls the width of the container to prevent it from stretching too far.
π Common Problem: Text Overflowing the Box
Sometimes, when text is long or unbreakable (like a long URL), it may overflow the box.
π₯ Problem Code:
<div class="broken-box">
ThisIsAReallyLongWordThatDoesNotBreakAndSpillsOutOfTheContainer
</div>
.broken-box {
border: 2px solid red;
width: 200px;
padding: 10px;
}
π§Ό Solution: Add word-wrap
and overflow-wrap
.broken-box {
border: 2px solid red;
width: 200px;
padding: 10px;
word-wrap: break-word;
overflow-wrap: break-word;
}
These properties force the long word to break and wrap to the next line, staying inside the box.
π Multi-Line Text with Proper Wrapping
To handle large blocks of text, ensure proper wrapping and spacing.
.text-box {
border: 1px solid #333;
padding: 20px;
width: 90%;
max-width: 600px;
line-height: 1.6;
box-sizing: border-box;
}
line-height
: Improves readability.max-width
: Keeps the box readable on larger screens.box-sizing: border-box
: Includes padding and border within the defined width.
π« Prevent Text from Exiting the Box Horizontally
Use the overflow
property when you’re dealing with dynamic content.
Example with Scroll:
.text-box {
border: 2px solid #666;
padding: 15px;
width: 250px;
height: 100px;
overflow: auto;
}
This creates a scrollable container if the content exceeds the height or width.
π± Responsive Tip
For mobile responsiveness:
.text-box {
width: 100%;
max-width: 500px;
margin: auto;
word-break: break-word;
}
This ensures the container and text stay within screen boundaries.
π§ Final Thoughts
To keep text within a bordered container:
- Use
padding
to add spacing inside the box. - Control
width
andmax-width
for layout. - Apply
word-wrap
,overflow-wrap
, orword-break
to handle long words. - Use
overflow: auto
orhidden
when necessary.
With these CSS techniques, your text will always remain neatly wrapped and visually contained within its borders, no matter the content length or screen size.