在图片前显示“ SALE”标签

时间:2019-05-12 20:39:40

标签: html css

我希望在图像之前显示'SALE'标签,我尝试使用'before'伪元素执行此操作,但是屏幕上似乎没有任何显示。

我正在尝试在黑色背景的圆圈内创建“ SALE”标签。

下面是我使用的代码

<span class"bag-image">
  <img src="https://images-na.ssl-images- 
amazon.com/images/I/71lDa7EbWSL._UY395_.jpg" class="image">
</span>

.bag-image::before{

background-color: #red;
content: 'SALE';
border-radius: 500px;
display: inline-block;
width: 100px;
height: 100px;

}

供参考:

LIKE THIS

https://codepen.io/anon/pen/rgLPdp

4 个答案:

答案 0 :(得分:0)

总而言之,您需要将position: relative属性添加到span,并将position: absolute属性添加到::after元素。像这样:

.bag-image {
  position: relative;
  display: block;
}

.bag-image::after {
  background-color: red;
  content: 'SALE';
  border-radius: 500px;
  display: block;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 0px;
  text-align: center;
  left: 100px;
}
<span class="bag-image">
  <img src="https://images-na.ssl-images-amazon.com/images/I/71lDa7EbWSL._UY395_.jpg" class="image">
</span>

使用left(可能还有top)属性将文本放置在所需位置。

答案 1 :(得分:0)

  1. 设置袋形图片类position: relative;
  2. position: absolute;之前制作袋形图像,并使用顶部/左侧或边距将其定位,并将行高设置为将SALE文本垂直居中。

您可以为伪类设置较低的z-index,以便仅可见上半部分,例如z-index: -1;

您可以在伪代码中使用margin-top: -2.5em; margin-left: 175px;来定位它。

div.bag-image {
  display: inline-block;

  /* just so that we  can see in the example */
  margin-top: 3em;   
}

div.bag-image:before {
  position: absolute;
  background-color: #ff0000;
  content: 'SALE';
  text-align: center;
  color: #ffffff;
  margin-top: -2.5em;
  margin-left: 175px;

  /* optionally make it a circle */
  border-radius: 9999px;
  height: 3em;
  padding: 1em;
  line-height: 3em;
}

/* just for clarity */
img.image {
  border: 1px solid #ccc;
}
<div class="bag-image">
  <img src="https://images-na.ssl-images-amazon.com/images/I/71lDa7EbWSL._UY395_.jpg" class="image">
</div>

答案 2 :(得分:0)

我想你想要这个。还要检查代码笔。Codepen
             

DT_DBDATE

答案 3 :(得分:0)

您可以尝试以下代码:

您的代码background-color: #red;声明为#red是错误的,它只是red的瞬间。  销售是我自己的父母相对的一个职位,您可以了解更多职位https://www.w3schools.com/css/css_positioning.asp

在这里还要写一些与代码有关的阴影元素,以供您回答。

也许可以解决您的问题。

===谢谢===

.bag-image {
  margin-top: 50px;
  position: relative;
  border: 1px solid red;
}
.bag-image img {
  display: block;
  max-width: 100%;
  height: auto;
  margin: 0 auto;
}
.bag-image::before{
  background-color: red;
  content: 'SALE';
  border-radius: 500px;
  display: inline-block;
  width: 100px;
  height: 100px;
  
  text-align: center;
  line-height: 100px;
  color: #fff;
  position:absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="bag-image">
  <img src="https://images-na.ssl-images-amazon.com/images/I/71lDa7EbWSL._UY395_.jpg" class="image">
</div>