DeFabregas
DeFabregas

Reputation: 49

CSS Operations with calc()

I have been working with the calc() CSS property and I have one doubt about it:

.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);
}

Like you see in the code I'm trying to subtract 100% - The nav WIDTH that it is in rem for the responsive mode, but obviously it doesn't work, is there any way to do this?

Upvotes: 3

Views: 1170

Answers (4)

dippas
dippas

Reputation: 60543

you can't use selectors in calc() as argument, if you want to subtract the nav's width then subtract nav's width already set:

.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.

Upvotes: 5

Marcin Zalewski
Marcin Zalewski

Reputation: 80

You can't substract whole element(nav), it must be exact value:

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

If you want to do it this way consider using preprocessor like Sass, you can add new variable and make it equal to some width value. You can substract then your width and this variable.

Sass way:

$nav-width: 10px;

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

Upvotes: 0

jeffjenx
jeffjenx

Reputation: 17457

I figured I would see if CSS variables could work and it seems to work for me in Chrome (though, not in Edge). I'm pretty sure compatibility issues might make this answer unacceptable until browser support increases, but I wanted to add it for future visitors or personal projects:

: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>

Upvotes: 1

hellojebus
hellojebus

Reputation: 3583

Unfortunately it doesn't work that way. It needs to be a predetermined value such as "10px" or "3rem".

However you can do this:

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

Upvotes: 0

Related Questions