When I needed to add or modify a CSS property of an element in Google Web Toolkit (GWT), I’d always do it like this :
widget.getElement().setAttribute("style", "align:right;");
However, if there was already any style information for defined for that element, it would be overwritten. You could get the current attributes first and then readd them along with your new info but there is a much cleaner way :
widget.getElement().getStyle().setProperty("align", "right");
Important! Note that when setting a style property, your need to use camel case for the property name.
//WRONG! myWidget.getElement().getStyle().setProperty("background-color", "red"); // RIGHT myWidget.getElement().getStyle().setProperty("backgroundColor", "red");
#1 by Marx on October 1, 2009 - 9:39 pm
Hi there. I found this by googling for “gwt add css property” and it was just what I needed. Thanks!
#2 by Jesse on December 22, 2009 - 5:16 pm
Howdy,
Thanks for your post, it was very helpful. Whenever i use the function setVisible(false), then call the setAttribute, the widget becomes visible again. What is it about setting a css attribute that causes the widget to be set to visible?
-Jesse
#3 by mailletf on December 22, 2009 - 5:33 pm
setAttribute resets all the css attributes that you don’t explicitly set when calling it. the default is visible so it becomes visible again. If you want to keep you widget invisible, use getStyle().setProperty to modify only the specific element you want to edit.
hope this helps
#4 by Jesse on December 22, 2009 - 5:42 pm
Awesome, thanks!
#5 by Thomas Käfer on February 11, 2010 - 8:07 am
I am trying to set a style property programatically, but when I call myWidget.getElement().getStyle() I get the Error
Method “getStyle” with signature “()Lcom/google/gwt/dom/client/Style;” is not applicable on this object
Definition of myWidget: protected @UiField HTML myWidget;