CSS Calc Number Division

CSS calc() - Multiplication and Division with unit-ed values

In CSS calc() division - the right side must be a <number> therefore unit based values cannot be used in division like this.

Also note that in multiplication at least one of the arguments must be a number.

The MDN has great documentation on this.

If you'd like a better way to do calculations you can use a preprocessor (I like Sass). That link will take you to their guides (on that page there's a section about operators).

css calc number division

The problem is with calc(2 / 3) you will just get a number without an unit. CSS can't display just a number as width. This would be like if you set width: 3 which obviously doesn't work.

If you want the percentage you will need to muliply it by 100%

width: calc(2 / 3 * 100%);

and if you really want the result in pixels multiply it by 1px

width: calc(2 / 3 * 1px);

CSS calc() and CSS Variables (Decimals and Division)

@TemaniAfif is right: the problem here is that calc division (at least in August 2018) always returns a float, and counter-reset (as well as many other CSS properties) only works with integer values. There's an issue on csswg-drafts for that:

Right now, calc() carefully tracks whether a numeric expression (no
units or %s) is guaranteed to resolve to an integer, or might resolve
to a more general number. This allows it to be used in places like
z-index safely.

However, it excludes some expressions that would be integral if
evaluated - for example, any division makes it non-integral, even in
an expression like calc(4 / 2).

Essentially, this proposal was accepted, but it seems to be not implemented in browsers - yet. For example, the relevant Chromium issue (which, to be precise, is about inability to use calc division result as param of CSS Grid) has been opened just two weeks ago.

CSS calc percentage width and division

Box-sizing:border-box

With box-sizing:border-box the dimension is calculated as, width = border + padding + width
of the content, and height = border + padding + height of the content.

Example

width = 100px + 2px border on both side = 4px + padding 5px on both side = 10px

The total will be 100px + 4px + 10px = 114px

With box-sizing:borderbox property

The total will be 100px because the border and padding is given from inside

CSS3 nested calc function using multiply and vw not rendering

You seem to expect the browser to figure out how much 200px (respectively 64px) is, as a ratio, from current browser width and automatically use that value.

Current browser implementation of calc only allows multiplication and division with numbers:

... : calc(100vw / 3) // valid
... : calc(1200px / 3) // valid
... : calc(1200vw / 200px) // NOT valid

See calc() current definition.

CSS calc() function

You cannot divide by units, only by numbers.



Related Topics



Leave a reply



Submit