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
Release: 2024-12-19 22:58:11
Original
177 people have browsed it

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>
Copy after login

With the following CSS:

.image {
    position: relative;
}

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

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

Using z-index for Overlapping

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

.text-container {
    z-index: 1;
}
Copy after login

Alternative Method

Using HTML2PDF

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

<div>
Copy after login

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');
Copy after login

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!

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