Home > Net >  How to add a label to images on website using ATTR?
How to add a label to images on website using ATTR?

Time:12-18

I'd like to attach a label to the images on my website, so I used the following CSS and HTML code.

CSS:

/* Image */
.image {
  border: 0;
  display: inline-block;
  position: relative; }
.image::after {
  content: "Photo credit: Me"; 
  position: absolute; 
  bottom: 0; 
  right: 3em; 
  font-size: 0.7em; 
  color:rgba(0, 0, 0, 0.175)}
  .image img {
    display: block; }
  .image.left, .image.right {
    max-width: 30%; }

HTML:

<div >
  <p> 
    <span >
      <img src="images/image_1.png">
    </span>
  </p>
</div>    

The code above works perfectly but I don't always want to show "Photo credit: Me" on my images. Instead, I want to set "Photo credit: Me" as a default text but show different text when specified. I tried using attr like below:

/* Image */
.image {
  border: 0;
  display: inline-block;
  position: relative; }
.image::after {
  content: attr(data-content, "Photo credit: Me"); /*<--Modified */
  position: absolute; 
  bottom: 0; 
  right: 3em; 
  font-size: 0.7em; 
  color:rgba(0, 0, 0, 0.175)}
  .image img {
    display: block; }
  .image.left, .image.right {
    max-width: 30%; }

<div >
  <p> 
    <span >
      <img src="images/image_1.png" data-content="Photo credit: Others">
    </span>
  </p>
</div>  

However, this code does not show anything on the images. What am I doing wrong?

Note: I'm using a template downloaded from https://html5up.net/editorial . There is a chance that some properties defined elsewhere in CSS are causing this issue...

CodePudding user response:

first, you shoud put the data-content on span, because the class .image is on span. second, till 2022-12-17, browser only supports basic attr() method, no one support fallback feature. if you want to implmenet fallback feature, you can use var to work around.

please check the code below: css

/* Image */
.image {
  border: 0;
  display: inline-block;
  position: relative; 
}
.image[data-content] {
    --test : attr(data-content); /* if image have data-content, then we defined the variable test) */
}
.image::after {
  content:  var(--test, "Photo credit: Me"); /*if var test not be define, we use default value  */
  position: absolute; 
  bottom: 0; 
  right: 3em; 
  font-size: 0.7em; 
  color:rgba(0, 0, 0, 0.175)}
  .image img {
    display: block; }
  .image.left, .image.right {
    max-width: 30%; }

html

<div >
  <p> 
    <span   data-content="Photo credit: Others">
      <img src="images/image_1.png">
    </span>
  </p>
</div>  
  • Related