19

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.

Wex
  • 15,539
  • 10
  • 64
  • 107
Cihad Turhan
  • 2,749
  • 6
  • 28
  • 45
  • I'm trying to make it for any kind of window size. If I plan to write it on js I should write both `.ready()` and `.resize()` functions which I don't want to do. – Cihad Turhan Aug 07 '12 at 08:18

4 Answers4

28

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?

Community
  • 1
  • 1
sandeep
  • 91,313
  • 23
  • 137
  • 155
3

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.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • I didn't know that. Seems very useful. – Cihad Turhan Aug 07 '12 at 08:06
  • The first that comes to my mind was less but, if the size of the element is dependent on the content then less would not be able guess the correct size, thus rendering invalid in some particular cases, other than that, it would be a perfect solution. But for this, CSS3 is better imho. – Umur Kontacı Aug 07 '12 at 09:02
2

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; }
Wex
  • 15,539
  • 10
  • 64
  • 107
2

Take a look at calc() function in CSS. Hopefully the support for this will increase in browsers.

roslav
  • 470
  • 3
  • 15