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

如何从JavaScript向CSS变量传入动态百分比(React场景)

问题:React动态设置子div高度为父容器的百分比

我创建了一个React组件,基于映射的动态数据进行渲染。外层div高度设为100%,希望内部子div在每次渲染时,根据计算出的百分比占据父容器对应垂直空间。例如组件渲染时关联的百分比为70%,就让子div占父容器70%的高度。

原实现代码

ReactJS

function Bucket({ numForChildDivHeight, numForParentDivHeight }) {

// 计算子div百分比并设置--dynamic-height
document.documentElement.style.setProperty('--dynamic-height',
    numForChildDivHeight / numForParentDivHeight);

    return (
        <div className='parent-div'>
            <div className='child-div'>
                // misc. information
            </div>
        </div>
    )
}

CSS

:root {
    --dynamic-height: 0%;
}

.parent-div {
    height: 100%;
}

.child-div {
    height: var(--dynamic-height);
}

问题分析

numForChildDivHeight / numForParentDivHeight返回的是小数(比如70%对应0.7),但CSS的height属性需要带%后缀的百分比字符串,直接传入小数会导致样式无法识别。

解决方案

方案1:修复CSS变量的赋值

将计算结果转换为带%的字符串后再传入CSS变量:

function Bucket({ numForChildDivHeight, numForParentDivHeight }) {
  // 计算百分比并拼接%符号
  const heightPercentage = (numForChildDivHeight / numForParentDivHeight) * 100 + '%';
  document.documentElement.style.setProperty('--dynamic-height', heightPercentage);

  return (
    <div className='parent-div'>
      <div className='child-div'>
        // misc. information
      </div>
    </div>
  )
}

CSS部分保持原代码不变即可,此时CSS变量能正确识别百分比值。

方案2:使用React内联样式(用户自行实现的优化方案)

直接通过内联样式动态设置高度,无需依赖CSS变量,更符合React组件化实践。修正原代码中style属性的传值错误(需传入样式对象而非字符串):

function Bucket({ numForChildDivHeight, numForParentDivHeight }) {
  const heightPercentage = (numForChildDivHeight / numForParentDivHeight) * 100 + '%';

  const bucketStyle = {
    height: heightPercentage,
  }

  return (
    <div className='parent-div'>
      <div className='child-div' style={bucketStyle}>
        // misc. information
      </div>
    </div>
  )
}

这种方式可以移除原CSS中与--dynamic-height相关的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:28