如何在CSS中将文本居中放置在图像上?

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

我想做一些类似下面的事情,但是我有困难,这是我目前的CSS

<style>
.image {
   position: relative;
}

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

在此处输入图像描述

当我使用背景图像时,我没有从html2pdf获得任何输出:

<style>
#image_container{
    width: 1000px;
    height: 700px;
    background-image:url('switch.png');
}
</style>
<a href="prints.php">Print</a>
<?php ob_start(); ?>
<div id="image_container"></div>
<?php 
$_SESSION['sess'] = ob_get_contents(); 
ob_flush();
?>

这是 fingerprint .php:

<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML($_SESSION['sess']);
$html2pdf->Output('random.pdf');
?>

推荐答案

像这样的怎么样:http://jsfiddle.net/EgLKV/3/

它是通过使用position:absolutez-index将文本放置在图像上完成的.

#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;
}
<div id="container">
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />
  <p id="text">
    Hello World!
  </p>
</div>

Html相关问答推荐

Flexbox响应式图像不会缩小

标签数据的XPath?

Bootstrap nav没有崩溃

我的Django应用程序中出现模板语法错误

如何显示自定义按钮以将产品添加到WooCommerce购物车?

带有排序元素的 CSS 网格

网格项未在同一行上对齐

HTML 重定向到当前服务器

如何使Bootstrap 5卡可点击

一旦大于最大限制,JQuery 取消 Select 复选框

排列卡片时遇到困难

模拟另一个输入值设置表单输入的数值

使用 calc 函数设置字体大小时 Flexbox 项目重叠

如何将背景与之前的内容正确对齐

无法使用 flexbox 裁剪图像

Mediawiki css/html 信息框创建空白行

将 div 放在图片旁边而不是下方

如何在react 中向按钮添加禁用属性?

如何使具有两个元素的 div 行在移动设备中响应

使用 golem 框架在shiny 的应用程序中存储背景图片的位置