Search code examples
safarigradientlinear-gradients

Safari linear gradient


I have a trouble using linear-gradient in Safari 15.2.

I wanna to create a block with fade effect at the end if children do not fit.

I have created an example: https://codepen.io/serejich/pen/xxXLvEG.

Code:

* {
  margin: 0;
}

.gradient-container {
  background-color: coral;
  width: 200px;
  height: 30px;
  position: relative;
  display: flex;
  align-items: center;
}

.elements {
  padding: 0 10px;
  display: flex;
  column-gap: 10px;
  overflow-x: hidden;
}

.elements p {
  color: #fff;
  white-space: nowrap;
}

.gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, rgba(255, 255, 255, 0) calc(100% - 50px), coral);
}
<div class="gradient-container">
  <div class="elements">
    <p>Element 1</p>
    <p>Element 2</p>
    <p>Element 3</p>
  </div>
  <div class="gradient"></div>
</div>

If you will open this in Safari, there would be something like a white area at the right of block.

What causes this and are there any ways to fix it?


Solution

  • This is a bug in safari that has to do with the way browsers interpolate between gradients.

    A common answer is to do what you did, using rgba(255, 255, 255, 0), however, Safari still interprets this as white and leads to that unwanted additional of white to the gradient. A fix is to use the same color you are transitioning from (coral in this case) and set it to transparent, which for coral would be rgba(255, 127, 80, 0). The example below uses the code from your pen with the fix applied for safari.

    See this stack for more

    * {
      margin: 0;
    }
    
    .gradient-container {
      background-color: coral;
      width: 200px;
      height: 30px;
      position: relative;
      display: flex;
      align-items: center;
    }
    
    .elements {
      padding: 0 10px;
      display: flex;
      column-gap: 10px;
      overflow-x: hidden;
    }
    
    .elements p {
      color: #fff;
      white-space: nowrap;
    }
    
    .gradient {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      /*RGBA equivalent to coral html color with alpha set to 0 - fixes safari interpolation bug*/
      background: linear-gradient(to right, rgba(255, 127, 80, 0) calc(100% - 50px), coral);
    }
    <div class="gradient-container">   
      <div class="elements">
        <p>Element 1</p>
        <p>Element 2</p>
        <p>Element 3</p>
      </div>
      <div class="gradient"></div>
    </div>