How to position text to center on an image with CSS

To position text to center on an image, use the transform property in CSS along with absolute positioning. This technique allows you to overlay text perfectly centered on any image.

Syntax

.container {
    position: relative;
}
.centered-text {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

Example

The following example demonstrates how to center text on an image −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        position: relative;
        display: inline-block;
        max-width: 600px;
    }
    
    .centered-text {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        font-size: 24px;
        font-weight: bold;
        color: white;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 10px 20px;
        border-radius: 5px;
        text-align: center;
    }
    
    img {
        width: 100%;
        height: auto;
        display: block;
    }
</style>
</head>
<body>
    <h2>Centered Text on Image</h2>
    <div class="container">
        <svg width="600" height="300" xmlns="http://www.w3.org/2000/svg">
            <rect width="100%" height="100%" fill="#4a90e2"/>
            <rect x="50" y="50" width="200" height="100" fill="#2c5aa0"/>
            <rect x="350" y="150" width="180" height="80" fill="#1e3d72"/>
            <circle cx="150" cy="200" r="30" fill="#ffffff"/>
            <text x="300" y="280" font-family="Arial" font-size="14" fill="white">Sample Image Background</text>
        </svg>
        <div class="centered-text">Perfectly Centered</div>
    </div>
</body>
</html>

The output of the above code is −

A blue geometric image appears with white text "Perfectly Centered" overlaid in the exact center. The text has a semi-transparent black background for better readability.

Key Points

  • Relative Container: The parent container must have position: relative
  • Absolute Positioning: The text element uses position: absolute with left: 50% and top: 50%
  • Transform: translate(-50%, -50%) shifts the element back by half its width and height to achieve perfect centering
  • Background: Adding a semi-transparent background improves text readability over images

Conclusion

The combination of absolute positioning and CSS transforms provides a reliable method to center text on images. This technique works consistently across different image sizes and is responsive by nature.

Updated on: 2026-03-15T13:12:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements