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
Release: 2024-12-21 16:50:20
Original
386 people have browsed it

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>
Copy after login
.image {
   position: relative;
}

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

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>
Copy after login
#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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template