Calc()输出意外值 [英] Calc() outputting unexpected value

查看:75
本文介绍了Calc()输出意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是使 #grid height #grid width 通过 calc(var(-grid-item-width)* 1.6),但似乎将-grid-item-width 视为视口宽度的百分比,而不是像素值。

What I would like to do is make the #grid height 160% of the #grid width via calc(var(--grid-item-width) * 1.6), but it appears that --grid-item-width is being treated as a percentage of the viewport width instead of a pixel value.

#grid 的高度远大于其宽度的160%,如下面的屏幕截图所示。

The height of #grid is much larger than 160% of its width as can be seen in the screenshot below.

:root {
  --gap: 26px;
  --grid-item-width: calc(100% - calc(var(--gap) * 4));
}

#grid {
  width: 100%;
  height: var(--grid-item-width); /* does not match */
  overflow-x: auto;
  display: grid;
  grid-gap: var(--gap);
  grid-auto-flow: column;
  grid-auto-columns: var(--grid-item-width); /* does not match */
}

当我将-grid-item-width 的值打印到控制台时,它返回 calc(100%-calc(26px * 4)),这显然无济于事。

When I print the value of --grid-item-width to console, it returns calc(100% - calc( 26px * 4)), which obviously does not help.

注释之一关于MDN的 calc()表示:

One of the notes about calc() on MDN states:


涉及宽度和百分比的数学表达式自动和固定布局表格中的表格列,表格列组,表格行,表格行组和表格单元格上的高度都可以视为已指定为自动。

Math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified.

这就是为什么 calc(var(-grid-item-width)* 1.6)在这种情况下产生意外输出的原因?

Is this why calc(var(--grid-item-width) * 1.6) has an unexpected output in this situation?

推荐答案

两个表达式都相同,但它们不会解析为

Both expression are the same BUT they will not resolve to the same value because they are applied to different porperties.

因此使用 calc(100%-calc(var(-gap)* 4)表示相同的值。 ),高度为 表示我们采用了父体高度的 100%(包含块),并删除了4个间隙。

So using calc(100% - calc(var(--gap) * 4)) with height means that we take 100% of the parent height (containing block) and we remove 4 gaps.

使用 calc(100%-calc(var(-gap)* 4)) grid-auto-columns 表示我们采用了元素宽度的100%,并删除了4个间隙。如果您的元素是代码中唯一的元素,那么它将是整个屏幕的宽度,因此您将最终使用屏幕的宽度。

Using calc(100% - calc(var(--gap) * 4)) with grid-auto-columns means that we take 100% of the element width and we remove 4 gaps. If your element is the only one on your code so it will be full screen width thus you will end using the width of the screen.

唯一的相同方法值是为了确保父级的高度与元素的宽度相同,或者避免使用百分比值并依赖会在两种情况下以相同方式解析的不同单位( px vw vh em 等)

The only way to have the same value is to be sure the height of the parent is the same as the width of the element OR avoid using percentage value and rely on different unit that will resolve the same way in both cases (px,vw,vh,em,etc)

请注意,与height一起使用的值可能无法自动 如果父元素上未设置未设置高度。

Note that the value used with height may fail to auto in case there is no height set on the parent element.

这篇关于Calc()输出意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆