Home > front end >  Understanding css calc() function
Understanding css calc() function

Time:05-23

Heydon Pickering wrote an article about mimicking container queries. He writes that the container's CSS should be as follows:

.container {
  display: flex;
  flex-wrap: wrap;
  --margin: 1rem;
  --multiplier: calc(40rem - 100%);
  margin: calc(var(--margin) * -1); /* excess margin removed */
}

and the container's children's CSS should be:

.container > * {
  min-width: calc(33% - (var(--margin) * 2)); /* remove from both sides */
  max-width: 100%;
  flex-grow: 1;
  flex-basis: calc(var(--multiplier) * 999);
  margin: var(--margin);
}

I'm just trying to understand how the --multiplier custom property works ie where 40rem - 100% what is 100% of?

Hope that makes sense.

CodePudding user response:

A Percentage in CSS is relative to the parent.
So in this case, the calc is as follow: 40rem - 100% [of the width of the parent].

The author explains it in their post:

the calculated value will be negative if the container is 40rem or more and positive if it's narrower than 40rem.

Examples:

  • If the parent element is 20rem, the result will be 40rem - 20rem, so 20rem;
  • If the parent element is 80rem, the result will be 40rem - 80rem, so -60rem;

In the calc() function you can actually mix many units (em, vmin, %, px, etc...), in the end they will all be unit of length and thus compatible with each other

CodePudding user response:

The 100% will just be in relation to whatever property the variable is being applied to.

--multiplier is just a variable, in this use case it is no different from just typing out its contents where it is being used.

So in this case:

flex-basis: calc(var(--multiplier) * 999);

is the same as

flex-basis: calc(calc(40rem - 100%) * 999);

And the 100% is in relation to the flex-basis property, and relative to the targets parent. You can read about the effect this has for flex-basis specifically in the flex-basis values section on MDN.

  •  Tags:  
  • css
  • Related