Search code examples
htmlcsssliderheight

How to stop a slider from changing its position according to the height of a div?


let Container = document.getElementById("Container1");
let slider = document.getElementById("slider1");

Container.setAttribute("style", "height: " + slider.value + "px");

slider.oninput = function() {
  Container.setAttribute("style", "height: " + this.value + "px");
};
.container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

#Container1 {
  width: 160px;
  height: 90px;
  border: 1px solid #000;
}

#slider1 {
  -webkit-appearance: none;
  background-color: black;
  width: 90px;
  height: 1px;
  transform: translateX(-50%) translateX(0.5cm) rotate(90deg);
  transform-origin: center;
}
<div class="container">
  <div id="Container1"></div>
  <input type="range" min="0" max="90" id="slider1" />
</div>

Here, it seems like the slider is changing its position with the height of the div element beside it. Why is this happening? How to stop it? On my attempt, I tried setting .container {height: 90px;} and the original problem got fixed but something strange happens. Why does that happen? Thanks!


Solution

  • try this

    I put height on the main div so all content remains in the static div.

    and transform: translateY(-50%) translateY(1.2cm) transform Y to 1.2cm

    align-items: start; so items are positioned at the beginning of the container

    let Container = document.getElementById("Container1");
    let slider = document.getElementById("slider1");
    
    Container.setAttribute("style", "height: " + slider.value + "px");
    
    slider.oninput = function() {
      Container.setAttribute("style", "height: " + this.value + "px");
    };
    .container {
        display: flex;
        justify-content: flex-start;
        align-items: start;
        height: 90px;
    }
    
    #Container1 {
      width: 160px;
      height: 90px;
      border: 1px solid #000;
    }
    
    #slider1 {
        -webkit-appearance: none;
        background-color: black;
        width: 90px;
        height: 1px;
        transform: translateX(-50%) translateX(0.5cm) translateY(-50%) translateY(1.2cm) rotate(90deg);
        transform-origin: center;
    }
    <div class="container">
      <div id="Container1"></div>
      <input type="range" min="0" max="90" id="slider1" />
    </div>