gpt4 book ai didi

javascript - 在小于其包含元素的居中图像上叠加文本

转载 作者:行者123 更新时间:2023-11-28 14:11:27 25 4
gpt4 key购买 nike

我有以下情况:

  1. 宽度小于页面宽度的图像。
  2. 图片需要在其父级 div(更宽)中居中。
  3. 叠加文本应显示在图像的一个 Angular 上。
  4. 无法拉伸(stretch)图片。图片将以其原始大小显示。
  5. 无法在 CSS 中设置图像大小,因为此模板将用于许多不同大小的图像。

所以我想出的代码在 https://jsfiddle.net/RoyiA/gdezys7j 中给出或者(必须在全屏模式下查看,以便图像居中):

@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}

.image-container {
position: relative;
font-family: Arial;
}

.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}

.image-text-block {
position: absolute;
display: block;
top: 100px;
left: 10px;
background-color: rgba(100, 100, 100, 0.5);
color: white;
padding-left: 10px;
padding-right: 10px;
}
<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-container">
<img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
<div class="image-text-block">
<h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
<p>Image: <a href="https://www.flickr.com/photos/151740882@N05/47029584231">Jane</a> by Mireille Lannoo</p>
</div>
</div>

我遇到的问题是,当图像居中时,文本 div 相对于其父级 div 的位置。如何解决这个问题?

最佳答案

我建议将图像容器 block 包装在另一个 div 中,目的是将其居中。这样,图像容器 block 就具有图像的宽度,并且标题框的绝对定位应该按预期工作。

.image-container {
position: relative;
font-family: Arial;
}

.image-center {
display: flex;
justify-content: center;
}

.image-center img {
display: block;
}

.image-text-block {
position: absolute;
display: block;
top: 10px;
left: 10px;
background-color: rgba(100, 100, 100, .5);
color: white;
padding-left: 10px;
padding-right: 10px;
}
<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-center">
<div class="image-container">
<img src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
<div class="image-text-block">
<h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
<p>Image: <a href="https://www.flickr.com/photos/151740882@N05/47029584231">Jane</a> by Mireille Lannoo</p>
</div>
</div>
</div>

关于javascript - 在小于其包含元素的居中图像上叠加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com