Home >Web Front-end >CSS Tutorial >How Can I Center Text Over an Image Using CSS?

How Can I Center Text Over an Image Using CSS?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 16:50:20392browse

How Can I Center Text Over an Image Using CSS?

Centering Text Over an Image with CSS

In this article, we will explore techniques to center text over an image using CSS.

Simple Solution

To achieve basic text centering over an image, adopt the following steps:

  • Use position: absolute for the text element.
  • Set the left property to 0 and the width property to 100%.
  • Horizontally center the text with margin: 0 auto.

Example:

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       <h2>Some text</h2>
    </div>
</div>
.image {
   position: relative;
}

.text {
   position: absolute;
   left: 0;
   width: 100%;
   margin: 0 auto;
}

Using z-Index

To ensure the text appears over the image, apply z-index to the text element with a higher value than the image's z-index.

Example:

<div>
#container {
    height: 400px;
    width: 400px;
    position: relative;
}

#image {
    position: absolute;
    left: 0;
    top: 0;
}

#text {
    z-index: 100;
    position: absolute;
    color: white;
    font-size: 24px;
    font-weight: bold;
    left: 150px;
    top: 350px;
}

The above is the detailed content of How Can I Center Text Over an Image Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn