我想在图像的顶部和中间放置一些文本。 .badge-card css styling
也无法更改,因为我的图像处于绝对位置。有关如何执行此操作的任何想法?
.badge-container {
position: relative;
text-align: center;
}
.badge-card {
top: -10px;
position: absolute;
left: -10px;
z-index: 9;
}
.badge-text-centered {
position: absolute;
top: 50%;
left: 50%;
color: black;
font-weight: bolder;
font-size: 14px;
transform: translate(-50%, -50%);
z-index: 10;
}
<div class="badge-container">
<img class="badge-card"
src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"
alt="Grapefruit slice atop a pile of other slices">
<div class="badge-text-centered">New<br> Image</div>
</div>
答案 0 :(得分:1)
有2种方法可以做到:1.使用flex标识id,简单有效,第二种使用绝对位置,您尝试过 问题是,当您对内部项目使用绝对位置时,它们的行为就像浮动项目,并且其高度和宽度不会增加父项的高度或宽度,在这种情况下,主容器没有高度可以使内部容器居中文字,您正面临此问题
解决方案:尝试在父容器上使用min-height或height,我使用100vh
使其高度等于主体高度。
.badge-container {
position: relative;
text-align: center;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.badge-card {
top: -10px;
position: absolute;
left: -10px;
z-index: 9;
height: 100%;
width: 100%;
object-fit: cover;
}
.badge-text-centered {
color: black;
font-weight: bolder;
font-size: 14px;
z-index: 10;
}
<div class="badge-container">
<img class="badge-card"
src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"
alt="Grapefruit slice atop a pile of other slices">
<div class="badge-text-centered">New<br> Image</div>
</div>
选中第二个选项,即您使用的方法,
.badge-container {
position: relative;
text-align: center;
height: 100vh;
}
.badge-card {
top: -10px;
position: absolute;
left: -10px;
z-index: 9;
object-fit: cover;
height: 100%;
width: 100%;
}
.badge-text-centered {
position: absolute;
top: 50%;
left: 50%;
color: black;
font-weight: bolder;
font-size: 14px;
transform: translate(-50%, -50%);
z-index: 10;
}
<div class="badge-container">
<img class="badge-card"
src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"
alt="Grapefruit slice atop a pile of other slices">
<div class="badge-text-centered">New<br> Image</div>
</div>
答案 1 :(得分:0)
https://codepen.io/divided7/pen/zYvVBGM我给你做了一个codepen。在这里,我只是将div浮动到了您想要的位置(在您的情况下为左侧),并删除了.badge-card
元素的样式。
.badge-container {
position: relative;
text-align: center;
float:left;
}
答案 2 :(得分:0)
在position: relative;
类中将位置更改为badge-card
.badge-container {
position: relative;
text-align: center;
}
.badge-card {
top: -10px;
position: relative;
left: -10px;
z-index: 9;
}
.badge-text-centered {
position: absolute;
top: 50%;
left: 50%;
color: black;
font-weight: bolder;
font-size: 14px;
transform: translate(-50%, -50%);
z-index: 10;
}
<div class="badge-container">
<img class="badge-card"
src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"
alt="Grapefruit slice atop a pile of other slices">
<div class="badge-text-centered">New<br> Image</div>
</div>