How To Create A Text Inside A Box Using HTML And CSS

To create a text inside a box using HTML and CSS, we can use several approaches to add borders around text elements and create visually appealing boxed content.

Syntax

selector {
    border: width style color;
    padding: value;
}

Approaches to Create a Text Inside a Box

Method 1: Using Span Element with CSS Border

This method uses a <span> element with CSS border and padding properties to create a box around specific text

<!DOCTYPE html>
<html>
<head>
<style>
    .textbox {
        border: 3px solid #333;
        padding: 8px 12px;
        display: inline-block;
        background-color: #f0f0f0;
        font-weight: bold;
    }
    
    h1 {
        font-size: 24px;
        margin: 20px 0;
    }
</style>
</head>
<body>
    <h3>Text Inside Box Example</h3>
    <h1>
        <span class="textbox">Tutorials</span>Point
    </h1>
</body>
</html>
A heading appears with "Tutorials" enclosed in a gray box with dark border, followed by "Point" in normal text styling.

Method 2: Using CSS Flexbox Layout

This approach uses flexbox properties to create multiple boxed text elements with flexible alignment

<!DOCTYPE html>
<html>
<head>
<style>
    .header {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 24px;
        margin: 20px 0;
    }
    
    .textbox1 {
        border: 3px solid #4CAF50;
        padding: 8px 12px;
        background-color: #e8f5e8;
        font-weight: bold;
    }
    
    .textbox2 {
        border: 3px solid #2196F3;
        padding: 8px 12px;
        background-color: #e3f2fd;
        font-weight: bold;
    }
</style>
</head>
<body>
    <h3>Flexbox Text Boxes Example</h3>
    <div class="header">
        <span class="textbox1">Tutorials</span>
        <span class="textbox2">Point</span>
    </div>
</body>
</html>
Two separate colored boxes appear side by side - "Tutorials" in a green box and "Point" in a blue box, aligned using flexbox.

Key Properties Used

Property Purpose
border Creates the box outline around text
padding Adds space inside the box around the text
display: inline-block Allows border/padding on inline elements
display: flex Creates flexible container for alignment

Conclusion

Creating text inside boxes can be achieved using CSS borders with span elements or flexbox layouts. The span method is simpler for single boxed elements, while flexbox provides better control for multiple aligned boxes.

Updated on: 2026-03-15T16:54:46+05:30

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements