skip to Main Content

I’ve got this CSS code snippet which is designed to apply a gradient background to specific text elements. The gradient’s configuration is determined by the width of the tag. Since there isn’t an alternative method to directly access the contextual text of any element using pure CSS, this width-based approach is being utilized:

span {
    width: fit-content !important;
    color: #0000;
    background:
        linear-gradient(rgb(247, 117, 110) 0 0) 0/calc(70px - 100%) 100%,
        linear-gradient(hsl(123, 90%, 40%) 0 0) 0/calc(100px - 100%) 100%;
    -webkit-background-clip: text;
    background-clip: text;
}

span::before {
    border-radius: 50%;
    content: "";
    display: inline-block;
    margin-right: 0.5em;
    width: 0.5em;
    height: 0.5em;
    vertical-align: 0.1em;
    background: #d2d7f5;
}
<span>Upcoming</span>
<span>Past</span>
<span>Upcoming</span>
<span>Past</span>

Is there a way to change the background color of the ::before pseudo-element based on the element as well?

2

Answers


  1. You can assign that background property value to a variable and use it on both the element and the pseudo-element.

    span {
        --custom-background:
            linear-gradient(rgb(247, 117, 110) 0 0) 0/calc(70px - 100%) 100%,
            linear-gradient(hsl(123, 90%, 40%) 0 0) 0/calc(100px - 100%) 100%;
        background: var(--custom-background);
    }
    
    span::before {
        background: var(--custom-background);
    }
    
    Login or Signup to reply.
  2. You need to redo your background. And in general, the :before element easily inherits the background properties, write them separately. Here is an example for you:

    span {
      color: #0000;
      background: linear-gradient(red, green);
      -webkit-background-clip: text;
      display: inline-flex;
      column-gap: .5rem;
    }
    
    span:before {
      content: '';
      width: .5em;
      background-image: inherit;
    }
    <span>Lorem<br>Lorem</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search