0

Is it possible in CSS to set an element's ::before content to a url passed as a data-attribute?

For example, if I have a bunch of testimonials and testimonial "headshots", I'm trying to pass them to CSS like so:

PHP / HTML:

$image_src = wp_get_attachment_image_src($image)[0];


echo '
    <div class="testimonial fp-card content-section content-section--has-center-image" data-image="' . $image_src . '">
       <div class="testimonial__text">' . $text . '</div>
    </div>';

SCSS:

.testimonial {
  &::before {
    content: attr(data-image); // This outputs the string URL. How can I use the string URL as an actual URL?
    position: absolute;
    top: -0.5rem;
    right: 50%;
    transform: translateX(-50%);
    // Etc
  }
}

Is there a way to pass the url from the data-image attribute to the ::before content as a valid URL?

I tried content: url(attr(data-image)), but that didn't work.

Sackadelic
  • 945
  • 1
  • 11
  • 21

1 Answers1

0

You can use CSS variables for this purpose.

You need to define a variable in CSS and assign a value to it through inline styles.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <style>
      .box {
        --avatar-url: "";

        position: relative;
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: var(--avatar-url);
      }

      .box::before {
        content: "";
        position: absolute;
        width: 150px;
        height: 150px;
        top: 0;
        left: 200px;
        border-radius: 50%;
        background: var(--avatar-url);
      }
    </style>

    <div class="box" style="--avatar-url: url('https://via.placeholder.com/150');"></div>
  </body>
</html>
DESSADER
  • 49
  • 3