1

NOTE: The MRE might not work in some browsers due to the poor support table.

@property --width1 {
  syntax: '<length>';
  inherits: false;
  initial-value: 20em;
}

@property --width2 {
  syntax: '<length>';
  inherits: false;
  initial-value: 200px;
}

div {
  margin: 30px;
  height: 30px;
  background: black;
  color: white;
  text-align: center;
}

#div1 { width: var(--width1); }
#div2 { width: 20em;          }
#div3 { width: var(--width2); }
#div4 { width: 200px;         }
<div id="div1">var(--width1) = 20em</div>
<div id="div2">20em</div>
<div id="div3">var(--width2) = 200px</div>
<div id="div4">200px</div>

In px, width of div3 is same as div4 as expected.

In em, div2's width was as expected. But in div1, it is almost as if the var(--width1) is ignored and the width is set to auto. Any way for the var(--width1) to work as expected?

Book Of Flames
  • 316
  • 3
  • 13
  • As you told in your post - it's **experimental** feature, so do not expect it to work properly – Justinas Aug 20 '21 at 09:30
  • @Justinas Means I need to stick with old manual form of changing width :( Isn't there an article related to this topic? – Book Of Flames Aug 20 '21 at 09:34
  • you cannot use relative unit there (you can also try with percentage it won't work). Unfortunately the Spec page is down right now to give you an answer: https://drafts.css-houdini.org/css-properties-values-api-1/#at-property-rule – Temani Afif Aug 20 '21 at 09:43
  • @TemaniAfif you can use percentage. If you change the data-type to `length-percentage` or just `percentage` . Not sure why `em` doesn't work because as you can see here https://developer.mozilla.org/en-US/docs/Web/CSS/length#units `em` are among `length` data type accepted units. – Mihai T Aug 20 '21 at 10:00
  • @MihaiT it's a length but it's a *relative* one. I always faced issue with them inside the initial value. You can try with `vw`, `ch`, etc. The behavior is a bit random sometimes – Temani Afif Aug 20 '21 at 10:05

1 Answers1

0

From the specification:

The initial-value must be computationally independent.

and

A property value is computationally independent if it can be converted into a computed value using only the value of the property on the element, and "global" information that cannot be changed by CSS.

In your case, em depend on the font-size value so it's not computationally independent

Temani Afif
  • 245,468
  • 26
  • 309
  • 415