You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使自定义Range Slider与相邻内联元素中线对齐?

实现span与Range Slider的中线对齐

我参考教程制作了自定义Range Slider,相关代码如下,现在希望让span元素的中线与Range Slider的中线对齐,请问如何实现?

原代码

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <p>Skills:</p>

    <div>
        <span>C++</span>
        <input type="range" name="volume" />
    </div>

    <div>
        <span>C#/.NET</span>
        <input type="range" name="cowbell" />
    </div>
    <script src="script.js"></script>
</body>

</html>

CSS

body
{
    background: rgb(41, 62, 72);
    color: white;
    font-size: 30px;
}

input[type=range] {
   -webkit-appearance: none;
   appearance: none;
   width: 300px;
   height: 10px;
   background: rgb(44, 160, 255);
   border-radius: 15px;
}

input[type=range]::-webkit-slider-thumb {
   -webkit-appearance: none;
   appearance: none;
   height: 20px;
   width: 20px;
   border-radius: 50%;
   background: rgb(41, 62, 72);
   border: 3px solid white;
   box-shadow: 0 0 0 1px rgb(41, 62, 72);
}

div
{
   height: 30px;
   margin-top: 30px;
   margin-bottom: 30px;
}

span
{
   margin-left: 10px;
   margin-right: 10px;
}

JavaScript

var inputs = document.querySelectorAll("input");

for (var input of inputs)
{
    console.log("processing")
    input.oninput = progressScript
    input.oninput()
}

function progressScript() {
    const sliderValue = this.value;
    this.style.background = `linear-gradient(to right, white ${sliderValue}%, rgb(44, 160, 255) ${sliderValue}%)`;
}

解决方案

有两种简单的实现方式:

方法1:使用Flex布局(推荐)

给包含span和input的父div添加display: flex和align-items: center属性,子元素会自动在垂直方向上居中对齐(即中线对齐)。

修改后的CSS代码:

body
{
    background: rgb(41, 62, 72);
    color: white;
    font-size: 30px;
}

input[type=range] {
   -webkit-appearance: none;
   appearance: none;
   width: 300px;
   height: 10px;
   background: rgb(44, 160, 255);
   border-radius: 15px;
}

input[type=range]::-webkit-slider-thumb {
   -webkit-appearance: none;
   appearance: none;
   height: 20px;
   width: 20px;
   border-radius: 50%;
   background: rgb(41, 62, 72);
   border: 3px solid white;
   box-shadow: 0 0 0 1px rgb(41, 62, 72);
}

div
{
   height: 30px;
   margin-top: 30px;
   margin-bottom: 30px;
   display: flex;
   align-items: center; /* 垂直居中对齐子元素 */
}

span
{
   margin-left: 10px;
   margin-right: 10px;
}

方法2:使用vertical-align属性

给span和range输入框直接设置vertical-align: middle,让它们基于中线对齐:

在原CSS中添加以下样式:

span, input[type=range] {
   vertical-align: middle;
}

内容的提问来源于stack exchange,提问作者user32882

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:55:25