如何使用 CSS 将文本定位在图像上

新手上路,请多包涵

如何在 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>

在此处输入图像描述

当我使用 background-image 时,我没有从 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();
?>

这是 prints.php:

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

原文由 Wern Ancheta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 340
2 个回答

这样的事情怎么样: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>

原文由 Ayush 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是使用响应式尺寸的另一种方法。它将使您的文本居中并保持其在其父项中的位置。如果你不希望它居中那么它更容易,只需使用 absolute 参数。请记住,主容器正在使用 display: inline-block 。有很多其他方法可以做到这一点,这取决于你在做什么。

基于 以未知 为中心

在此处工作的代码笔示例

HTML

 <div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

 .containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

原文由 Ghost Echo 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题