htmlmeter

How to specify starting value of <meter> tag not from zero?


Suppose, I want to specify (highlight) the range of meter tag from 0.4 to 0.6 values. How can I do that?

<meter max="0.6" min="0.4"></meter>

I want to do something like this:

Meter with range


Solution

  • You can set the background of your meter, in our case it has a lightgray color up to 40%, changes to green and keeps it that way up to 60% from whence it turns to lightgray again.

    meter {
      background: linear-gradient(
        90deg,
        lightgray 40%,
        green 40%,
        green 60%,
        lightgray 60%
      );
      border-radius: 10px;
      border: 1px solid grey;
    }
    <meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="0">at 50/100</meter>

    You can also programmatically change it, like here

    let state = {
        lower: 40,
        greater: 60
    }
    
    function change(what, how) {
        state[what] += how;
        let {lower, greater} = state;
        document.getElementById("fuel").style.background = `
        linear-gradient(
            90deg,
            lightgray ${lower}%,
            green ${lower}%,
            green ${greater}%,
            lightgray ${greater}%
        )
        `;
    }
    #fuel {
      background: linear-gradient(
        90deg,
        lightgray 40%,
        green 40%,
        green 60%,
        lightgray 60%
      );
      border-radius: 10px;
      border: 1px solid grey;
    }
    <input type="button" value="<" onclick="change('lower', -1)">
    <input type="button" value=">" onclick="change('lower', 1)">
    <meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="0">at 50/100</meter>
    <input type="button" value="<" onclick="change('greater', -1)">
    <input type="button" value=">" onclick="change('greater', 1)">

    Each time you click an arrow, the lower bound changes if one of the first two is the one you clicked, otherwise the greater bound will be changed.