Home > Mobile >  change background color via CSS after a certain width
change background color via CSS after a certain width

Time:09-30

I made a program in react js ,to analyze user microphone volume. The volume range can be in between 1 - 20; so in order to show it on the UI ,I'm just multiplying it with 5 and setting it as the width percentage of a div. my code :

<div id="default_audio_view">
      <div
        className="_inside_default_view"
        style={{ width: `${volume * 5}%` }}
      ></div>
    </div>

css:

#default_audio_view {
  background-color: #e8e8e8;
  width: 100%;
  height: 20px;
  position: relative;
  display: flex;
  align-items: center;
}
._inside_default_view {
  position: absolute;
  height: 16px;
  background: linear-gradient(
    to right,
    rgb(32, 235, 32) 0 29.3%,
    rgb(255, 255, 24) 33.3% 62.6%,
    rgb(221, 16, 16) 66.6% 100%
  );
}

Now the linear gradient considering only the _inside_default_view's width as 100%. How can I solve it?

it's the result

CodePudding user response:

You can add another background for a full-width colorful bar on a new element called _inside_default_view_background, and use the existing _inside_default_view with a grey right-to-left background like below

#default_audio_view {
  background-color: #e8e8e8;
  width: 100%;
  height: 20px;
  position: relative;
  display: flex;
  align-items: center;
}
._inside_default_view {
  background-color: #e8e8e8;
  position: absolute;
  height: 16px;
  z-index: 1;
  right: 0;
}

._inside_default_view_background {
  position: absolute;
  height: 16px;
  width: 100%;
  background: linear-gradient(
    to right,
    rgb(32, 235, 32) 0 29.3%,
    rgb(255, 255, 24) 33.3% 62.6%,
    rgb(221, 16, 16) 66.6% 100%
  );
  z-index: 0;
}
<div id="default_audio_view">
  <div  style="width: 50%;"></div>
  <div ></div>
</div>

With the above technique, you also need to modify your formula from 100% to back (instead of 0% to 100%)

<div id="default_audio_view">
      <div
        className="_inside_default_view"
        style={{ width: `${100 - (volume * 5)}%` }}
      ></div>
      <div ></div>
    </div>

CodePudding user response:

@Arijit you'll need to dynamically update the style based on state, you could also use the animate method in JS, though browser support might be spotty for it as it's still fairly new at the time of writing this.

  • Related