Documentation versions (currently viewingVaadin 24)

Dynamic Styling Using the Element API

How to style elements using dynamic class names or inline styles.

You can use the Element API to style elements using dynamic class names or inline styles.

The Element API includes two methods that facilitate styling:

  • getClassList(): gets the set of CSS class names used for the element

  • getStyle(): gets the style instance to manage element inline styles

Modifying CSS Classes on an Element

You can use the getClassList() method to get a collection of CSS class names used for the element. The returned set can be modified to add or remove class names.

Example: CSS style rules.

.blue {
  background: blue;
  color: white;

Example: Using the getClassList() method to dynamically modify the class names of an element.

button.setText("Change to blue");
    e -> button.getClassList().add("blue"));

Example: Using the getClassList method to add and remove classes.


// returns "error critical".
  • The element.getProperty("className") method gets a set of all classes as a concatenated string.

You can’t modify classList or className properties directly using the setProperty() methods.

You can set and get an element’s class attribute using:

  • element.setAttribute("class", "foo bar"): this clears any previously set classList property.

  • element.getAttribute('class'): this returns the contents of the classList property as a single concatenated string.

Using the Style Object

You can set and remove inline styles for an element using the Style object returned by the element.getStyle() method. Style property names can be formatted in camel case (for example, backgroundColor) or kebab case (for example, background-color).

Example: Using the getStyle() method for dynamic inline styling.

Element input = ElementFactory.createInput();
button.setText("Change to the entered value");
    e -> button.getStyle().set("background",

Example: Setting and removing style objects using the element.getStyle() method.

element.getStyle().set("color", "red");
element.getStyle().set("fontWeight", "bold");
element.getStyle().set("font-weight", "bold");