CSS custom properties (variables) for box model

前端 未结 2 916
你的背包
你的背包 2020-12-20 22:52

I am trying to have CSS variables for box model properties. I want to support both setting a value for all sides as well as individual sides. I want to have default values,

相关标签:
2条回答
  • 2020-12-20 23:33

    The fallback value works only if the variable --border-width is not defined:

    The custom property's fallback value, which is used in case the custom property is invalid in the used context.

    MDN

    See demo below:

    :root {
      --border-width-top: 0;
      --border-width-right: 0;
      --border-width-bottom: 0;
      --border-width-left: 0;
      /*--border-width: 0;*/
    }
    
    div {
      border-color: red;
      border-style: solid;
      border-width: var(--border-width, var(--border-width-top) var(--border-width-right) var(--border-width-bottom) var(--border-width-left));
    }
    
    div {
      --border-width-top: 10px;
    }
    <div id="app">
      <h1>TypeScript Starter</h1>
    </div>

    0 讨论(0)
  • 2020-12-20 23:45

    You can unset the value using initial to use the fallback one:

    :root {
      --border-width-top: 2px;
      --border-width-right: 2px;
      --border-width-bottom: 2px;
      --border-width-left: 2px;
      --border-width: 0;
    }
    div {
      margin:5px;
      border-color: red;
      border-style: solid;
      border-width: var(--border-width, var(--border-width-top) var(--border-width-right) var(--border-width-bottom) var(--border-width-left));
    }
    
    
    div.box {
      --border-width:initial;
      --border-width-top: 10px;
    }
    <div>some content</div>
    <div class="box">some content</div>

    from the the specification:

    The initial value of a custom property is an empty value; that is, nothing at all. This initial value has a special interaction with the var() notation, which is explained in the section defining var().

    and

    To substitute a var() in a property’s value:

    1. If the custom property named by the first argument to the var() function is animation-tainted, and the var() function is being used in the animation property or one of its longhands, treat the custom property as having its initial value for the rest of this algorithm.
    2. If the value of the custom property named by the first argument to the var() function is anything but the initial value, replace the var() function by the value of the corresponding custom property. Otherwise,
    3. if the var() function has a fallback value as its second argument, replace the var() function by the fallback value. If there are any var() references in the fallback, substitute them as well.
    4. Otherwise, the property containing the var() function is invalid at computed-value time
    0 讨论(0)
提交回复
热议问题