Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS value as mathematical expression

Tags:

html

css

Is there anyway that I can write a css value as mathematical expression? Example:

div{
    height: 50% + 30px;
    width: 40em - 5px;
   }

If there is, it would be perfect.
PS: I don't want to do it with JS or JQuery.

like image 682
Cihad Turhan Avatar asked Aug 07 '12 08:08

Cihad Turhan


People also ask

How do you do maths with CSS?

It is not possible to do mathematic operations inside CSS natively. You could use JavaScript to change CSS properties on page load, but this is a pain and must be done every page load making your page slow. You'll need to use a CSS preprocessor like LESS, Stylus, or SASS.

Does CSS have math?

The CSS math functions allow mathematical expressions to be used as property values. Here, we will explain the calc() , max() and min() functions.

What is CSS expression?

CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They're supported in Internet Explorer version 5 and later.


3 Answers

You can achieve this with css3 calc(). Write like this:

div{
    width: 40%;
    width: -webkit-calc(40% - 5px);
    width: -moz-calc(40% - 5px);
    width: calc(40% - 5px);
    height:50%;
    height: -webkit-calc(50% + 50px);
    height: -moz-calc(50% + 50px);
    height: calc(50% + 50px);
    background: green;
    color: white;
    position:absolute;
}

Check this http://jsfiddle.net/3QUw6/

Check this discussion for more Is it possible to make a div 50px less than 100% in CSS3?

like image 130
sandeep Avatar answered Sep 28 '22 00:09

sandeep


You can not do this with CSS, but you could (and much more) with a CSS preprocessor, like LESS, SASS or my favorite Stylus. THe final output is plain old CSS, but it must be compiled first.

like image 37
Billy Moon Avatar answered Sep 28 '22 00:09

Billy Moon


Both padding and margin can be used to add to the dimensions of objects. I suggest you read up on the box model.

HTML:

<div id="container">
    <div class="wrapper">
        <div>...</div>
    </div>
</div>

CSS:

.wrapper { 
    width: 40em;
    height: 50%;
    padding: 15px 0; /* Top and bottom padding of 15px */ }

/* Block-level element will take up 100% of the 
  container width, minus {margin_right} + {marign_left} */
.wrapper > div { margin: 0 0 0 5px; }
like image 31
Wex Avatar answered Sep 27 '22 23:09

Wex