CSS3 calculator

    Hello, habrauser!

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



    Disclaimer


    To begin with, we must immediately understand that JavaScript is indispensable here, because we must somehow assign our mathematical expression to a certain property (for example, margin), and then read its result.
    It’s also all done by Just for Fun and has no practical meaning.

    The operators +, -, / and * are available to us.
    According to the standard, this property can be used wherever possible the use of numerical units (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 a unit of measure for length, deg is an angle, etc.
    Interest 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 indentation of 100px 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):
    Verifies that the divisor is always a number and not equal to 0.

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


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

    This happens because the width cannot be negative.

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

    As a result, it turned out:
    CSS3 Calculator

    The principle of operation is simple:
    1.) We get the expression from input.
    2.) Assign it to the margin property (such that it supports negative numbers).
    3.) Read the calculated result in pixels.

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

    Also popular now: