How can i export shorthand CSS properties (border, border-left, border-right…) as CSS variables

北战南征 提交于 2021-01-29 14:48:16

问题


If i do this:

.a {
        border: var(--a-border);
        border-left: var(--a-border-left);
        border-right: var(--a-border-right);
        border-top: var(--a-border-top);
        border-bottom: var(--a-border-bottom);
}

Setting --a-border never works because individual properties like a-border-left have reset the value. What i'm thinking is that, i'm not giving any default values on those exported variables. Therefore, if --a-border is set, it should take precedence over other unset values.


回答1:


As I explained in this previous answer when using border-left: var(--a-border-left) it means that border-left will always have a valid value whataver the definition of the CSS variables. Considering this your shorthand property will always be ignored because the longhand ones will always override it.

One fix is to consider the fallback property and redefine the variable used inside the shorthand in each individual propery:

.a {
  border: var(--a-border);
  border-left: var(--a-border-left,var(--a-border));
  border-right: var(--a-border-right,var(--a-border));
  border-top: var(--a-border-top,var(--a-border));
  border-bottom: var(--a-border-bottom,var(--a-border));
  
  
  width: 200px;
  height: 100px;
  display:inline-block;
}

:root {
  --a-border: 5px solid red;
}
<div class="a"></div>

<div class="a" style="--a-border-bottom:5px solid green"></div>


来源:https://stackoverflow.com/questions/60361012/how-can-i-export-shorthand-css-properties-border-border-left-border-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!