【问题标题】:Can you combine CSS variables to include the property and the value?你可以结合 CSS 变量来包含属性和值吗?
【发布时间】:2022-07-06 23:17:56
【问题描述】:

虽然我知道你不能像这样写变量

root: {
--aic: align-items:center;;
}

有没有办法通过单独组合各个部分来解决这个问题?这里明显的obstical是变量内部的冒号的要求。

root: {
    --ai: align-items:;
    --center: center;
    --aic:
    var(--ai)
    var(--center);
    }

.myclass {var(--aic);}

【问题讨论】:

  • 不,很遗憾不可能
  • 好的,谢谢 :)
  • 我希望是这样,在尝试创建可自定义的模板/框架之前,我一直在走这条路
  • 如何在文本“colon-goes-here”中使用一个支架,然后在渲染时使用 JS 即时换出?可能是性能问题,但只是一个想法?
  • 也许,我能想到的唯一方法是使用data-attributes,然后用JS创建一个<style>元素——虽然它会变得混乱,而且会有性能肯定的考虑。为什么不直接用类来设置呢?例如,您希望将自定义属性作为声明的最终目标是什么?

标签: css


【解决方案1】:

根据我对您问题的评论,您可以使用类来实现类似的目标。但是您不能将自定义属性用作 CSS 属性,只能使用值

:root { --size: 1rem }

.varText, .varPad { border: 1px solid red }

.varText { font-size: var(--size) }
.varPad { padding: var(--size) }
<div class="varText varPad">
  Size Text and Padding to root variable
</div>
<div class="varText varPad" style="--size: 2rem">
  Size Text and Padding to inline variable
</div>
<div class="varText">
  Size Text only to root variable
</div>
<div class="varText" style="--size: 2rem">
  Size Text only to inline variable
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多