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

How to Center Text Over an Image Using CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 22:58:11117browse

How to Center Text Over an Image Using CSS?

Positioning Text over an Image with CSS

This article will demonstrate how to align text centrally over an image using CSS.

Problem Scenario

You may encounter the following situation:

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       <h2>Some text</h2>
    </div>
</div>

With the following CSS:

.image {
    position: relative;
}

h2 {
    position: absolute;
    top: 200px;
    left: 0;
    width: 100%;
    margin: 0 auto;
    width: 300px;
    height: 50px;
}

But the text remains misaligned.

Solution

Using CSS Positioning

To position the text over the image, use CSS positioning:

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

.text-container {
    position: absolute;
    top: 50%;  /* Position the text vertically */
    left: 50%;  /* Position the text horizontally */
    transform: translate(-50%, -50%);  /* Center the text */
    color: white;
    font-size: 24px;
    text-align: center;
}

Using z-index for Overlapping

To ensure the text overlays the image, use z-index:

.text-container {
    z-index: 1;
}

Alternative Method

Using HTML2PDF

To create a PDF containing the image and centered text, you can use HTML2PDF. First, render the HTML content:

<div>

Next, use HTML2PDF to convert the HTML to PDF:

require_once('html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML(file_get_contents('image-container.html'));
$html2pdf->Output('random.pdf');

Note that you may need to adjust the CSS and HTML slightly to ensure proper rendering within the HTML2PDF environment.

The above is the detailed content of How to 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