I want to position a div ".indicator" just where a li element starts, so for example, if I want to position the div in relation to the second li, I do:
indicator.style.left = li[1].getBoundingClientRect().left+"px";
This is my code:
var li = document.querySelectorAll(".ulcontainer > li");
var indicator = document.querySelector(".indicator");
indicator.style.left = li[1].getBoundingClientRect().left+"px";
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.ulcontainer {
white-space: nowrap;
padding: 0;
position: relative;
}
.ulcontainer li {
list-style: none;
display: inline-block;
border: 1px solid;
padding: 0 20px;
}
.indicator {
background-color: red;
display: inline-block;
position: relative;
}
<ul class="ulcontainer">
<li>OPTION 1</li><li>OPTION 2</li><li>OPTION 3</li>
</ul>
<div class="indicator">indicator</div>
The problem is that the div getBoundingClientRect().left is not returning the correct value for the li elements. If you run the example, you will see that ".indicator" is not starting in the beggining of the current li.
Why is not getBoundingClientRect().left returning the current value?
display: inline-block;and/orposition: relative;. Try messing around with those and tell me if that did anything.