views:

67

answers:

3

I'm looking for a way to do something like this:

// style.css
@def borderSize '2px';

.style {
  width: borderSize + 2;
  height: borderSize + 2;
}

where the width and height attributes would end up having values of 4px.

A: 

I would also love somehting like that, but it's not possible. Even in CSS 3 their is nothing planned like this.

If you really want to make something like that, one possibility is to use php and configure your webserver, so that .css files are parsed by php.

So you could do something like

<?
  $borderSize = 2;
?>

.style {
  width: <? borderSize+2 ?>px;
  height: <? borderSize+2 ?>px;
}

But as this is no 'standard' way, i think its better to not do it.

Marks
+1  A: 

Mozilla kind-of-sort-of-not-really supports this with it's CSS calc() function.

This example shamelessly stolen (with attribution!) from Ajaxian

/*
* Two divs aligned, split up by a 1em margin
*/
#a {
  width:75%;
  margin-right: 1em;
}
#b {
  width: -moz-calc(25% - 1em);
}

It's not cross-browser, and it's probably only barely supported by even bleeding-edge versions of Firefox, but there's at least being progress made in that direction.

Jason Hall
+3  A: 

Sometimes I use the following:

@eval BORDER_SIZE_PLUS_2 2+2+"px"; /* GWT evaluates this at compile time! */

Oddly, this only works, if you don't put any spaces between the + operator and the operands. Also, in @eval you can't use constants that were previously defined by @def. You can however use constants that are defined as static fields in one of your Java classes:

@eval BORDER_SIZE_PLUS_2 com.example.MyCssConstants.BORDER_SIZE+2+"px";

Or you could let the calculation be performed completely by Java:

@eval WIDTH com.example.MyCssCalculations.width(); /* static function, 
                                                      no parameters! */
@eval HEIGHT com.example.MyCssCalculations.height();
.style {
    width: WIDTH;
    height: HEIGHT;
}

But what I would actually like to do is very similar to your suggestion:

@def BORDER_SIZE 2;
.style {
    width: value(BORDER_SIZE + 2, 'px'); /* not possible */
    height: value(BORDER_SIZE + 3, 'px');
}

I don't think that's possible in GWT 2.0. Maybe you find a better solution - here's the Dev Guide page on this topic.

Chris Lercher
+1 Nice findings - I really wish the GWT team would take some time to improve the CssResource handling - there's so much potential there, like Jason pointed out with the `calc()` function from Mozilla.
Igor Klimer
Thanks for the answer, unfortunately my underlying reason for asking the question was to have the @def variable populated by an image resource, for example replace @def borderSize '2px' with @def borderSize value('icon.getWidth', 'px'); But I'll definitely be using those simple arithmetic ops in the future
Matt