Home >Web Front-end >CSS Tutorial >How to Center Text Over an Image Using CSS?
This article will demonstrate how to align text centrally over an image using CSS.
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.
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; }
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!