Issue
I have a slider that goes from 1 to 12. I would like the thumb to perfectly align with all the numbers above it when I move it up and down.
This is what I have so far, but as you can see, it is still slightly off.
Is there a way to achieve this?
body {
height: 100vh;
display: flex;
}
.container {
margin: auto;
width: 400px;
}
span {
display: block;
width: 1ch;
}
.numbers {
display: flex;
justify-content: space-between;
padding-left: .4em;
}
<div class="container">
<div class="numbers">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span>
</div>
<input style="width: 100%;" type="range" min="1" max="12" name="" id="" />
</div>
Solution
We can configure the number spans so they all have the same width and center text alignment. By setting their initial width to zero we negate the effect of their contents, which vary in size (1 vs 10, for example).
We can use flexbox on the slider as well, giving it the same flex-grow value as twice our 12 numbered spans. This lets us use half-widths for spacing. We add a span on each side of it with a value of half that of the numbered spans, shifting things over properly.
Finally, some margin tweaks get things pixel-perfect (in Chrome, at least).
Note that I've changed the primary width to a relative value so you can see that this works at any size. Have a look at the full screen demo.
The primary drawback here is that we have quantities hard-coded in the CSS. If the slider range changes, so must the CSS. Ideally we'd find a fully flexible solution.
If I'm not making sense, have a look at https://css-tricks.com/snippets/css/a-guide-to-flexbox.
body {
height: 100vh;
display: flex;
}
.container {
margin: auto;
width: 75vw;
}
.numbers,
.slider {
display: flex;
justify-content: space-between;
}
.numbers span,
.slider span {
width: 0;
flex-grow: 1;
text-align: center;
}
.slider span {
flex-grow: 1;
}
.slider input {
flex-grow: 24;
margin-left: -2px; /* account for UI sizing */
margin-right: -2px; /* account for UI sizing */
}
<div class="container">
<div class="numbers">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span>
</div>
<div class="slider">
<span><!-- half --></span>
<input type="range" min="1" max="12" name="" value="1" id="" />
<span><!-- half --></span>
</div>
</div>
Answered By - isherwood
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.