如何使用 CSS 将文本放置在图像上
P粉696605833
P粉696605833 2023-08-23 17:18:53
[CSS3讨论组]

如何在 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();
?>

这是 prints.php:

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


P粉696605833
P粉696605833

全部回复(2)
P粉041856955

这是使用响应式尺寸的另一种方法。它将保持您的文本居中并保持其在父级中的位置。如果您不希望它居中,那就更简单了,只需使用 absolute 参数即可。请记住,主容器正在使用 display: inline-block。还有许多其他方法可以实现此目的,具体取决于您正在处理的内容。

基于以未知为中心

这里是工作的 codepen 示例

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;
}
P粉349222772

像这样的怎么样: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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号