CSS 使用 calc() 的操作

CSS Operations with calc()

我一直在使用 calc() CSS 属性,我对此有一个疑问:

.main {
  display: block;
  margin-left: 4rem;
  width: (100% - nav);
  background: red;
}
nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 4rem;
  height: 100vh;
  background: #292929;
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

就像你在代码中看到的那样,我正在尝试减去 100% - 导航 WIDTH 它在 rem 中用于响应模式,但显然它没有工作,有什么办法吗?

不幸的是,它不是那样工作的。它需要是一个预定的值,例如“10px”或“3rem”。

但是你可以这样做:

.main {
    /* ... */
    width: calc(100% - 4rem);
}

你不能使用 calc() 中的选择器作为参数,如果你想减去 navwidth 然后减去 navwidth 已经设置:

.main {
  width: calc(100% - 4rem);
  /* mores styles */
}

The calc() CSS function can be used anywhere a <length>, <frequency>, <angle>, <time>, <number>, or <integer> is required.

.....

Expressions

The expression can be any simple expression combining the following operators, using standard operator precedence rules:

+ Addition.

- Subtraction.

* Multiplication. At least one of the arguments must be a <number>.

/ Division. The right-hand side must be a <number>.

The operands in the expression may be any length syntax value. You can use different units for each value in your expression, if you wish. You may also use parentheses to establish computation order when needed.

我想我会看看 CSS 变量是否可以工作,它似乎在 Chrome 中对我有用(尽管在 Edge 中不行)。我很确定在浏览器支持增加之前,兼容性问题可能会使这个答案不可接受,但我想为未来的访问者或个人项目添加它:

:root {
  --nav-width: 5em;
}

nav {
  background: red;
  width: var(--nav-width);
  height: 1em;
}

div {
  background: blue;
  width: calc(100% - var(--nav-width));
  margin-left: var(--nav-width);
  height: 1em;
}
<nav></nav>
<div></div>

不能减去整个元素(nav),它必须是精确值:

<length>, <frequency>, <angle>, <time>, <number>, or <integer>

如果你想这样做,考虑使用像 Sass 这样的预处理器,你可以添加新变量并使其等于某个宽度值。你可以减去你的宽度和这个变量。

Sass 方式:

$nav-width: 10px;

.main {
display: block;
margin-left: 4rem;
width: (100% - $nav-width);
background: red;
}