📜 ⬆️ ⬇️

CSS3 Calculator

Hello, habrauzer!

Sitting recently and flipping through developer.mozilla.org came across a description of -moz-calc ();
In short, this property is used to calculate expressions directly in CSS.
It was then that the idea was born to make a calculator that would be considered through this ingenious property.
What came of this can be judged by this screenshot:



Disclaimer


To begin with, we must immediately understand that without JavaScript there is not enough, for we must somehow assign a certain mathematical property (eg, margin) to our mathematical expression, and then read its result.
It is also done by Just for Fun and does not carry any practical meaning.
')
We have operators +, -, / and *.
According to the standard, this property can be used wherever it is possible to use numeric units of measurement (px, ms, s,%, vh, pt, em, ex, deg, grad, etc.)

"+" and "-"

These operators verify that the numbers on both sides of the operator are of the same type.
By type is meant that cm is the unit of measurement for length, deg for angle, etc.
Percentages can be used when they can be converted to the type of property for which the expression is calculated.

An example of a centered element with 100px padding on each side.
#elem { height: 100px; margin: 0 auto; width: -moz-calc(100% - 200px); border: 1px solid black; } 


* and /

"*" (Multiplication):
The operator checks that at least one of the multiplied values ​​is a number.
"/" (Division):
Checks that the divisor is always a number and not equal to 0.

An element having a width of 1/6 of the width of the page.
 #elem2 { width: -moz-calc(100% / 6); } 


The value assigned is not always equal to the value received.
For example:
 width: -moz-calc(1px - 10px); /* Width = 0 */ 

This happens because the width cannot be negative.

Currently, CSS3 calc is implemented in Firefox 4+ and IE9 +.
In Firefox, it is implemented with the prefix -moz-, in IE without the prefix.
There is a bug in Webkit bug tracker that tells us about the status of implementation.
But due to my lack of IE9 and the ability to check, this calculator only works in Firefox 4+.

The result was this:
CSS3 Calculator

The principle of operation is simple:
1.) Get an expression from input.
2.) Assign its property to the margin (Such that supports negative numbers).
3.) Read the calculated result in pixels.

Bugs:
1.) Strange rounding numbers (a la 22/7)

Source: https://habr.com/ru/post/131507/


All Articles