DS Vaadin Flow Gradle Plugin May 29th, 2019

Using Cascading Style Sheets (CSS)

Using CSS is the default way of styling Vaadin applications.

A simple example

When you create a new project, a default CSS file is created to help you get started. Here is an example of some CSS:

myproject-theme.css

1
2
label { color: green; }
label.clicked { color: red; }

In this case we are style an element of type label to have a text color of green and when the user clicks on the label and a new css-class is added to the label it becomes red. This is just a very simple example of how CSS can be used.

For more information about the CSS syntax checkout this excellent guide.

Where should I put my CSS files?

CSS files should be put in the src/main/webapp/frontend/styles directory.

This directory is specially treated by the DS Vaadin Flow Gradle Plugin and allows you to use CSS files to style also parts of the Shadow DOM leveraging the plugin’s auto-wrapping feature.

If you put CSS files outside of this directory your CSS will not be applied to the Shadow DOM.

Injecting CSS files into your Vaadin application

The way you tell Vaadin about a new CSS file is to annotate a Vaadin class with the @HTMLImport annotation.

For example, when you create a new project your UI class will look like this:

MyProjectUI.java

1
2
3
@HtmlImport("frontend://styles/myproject-theme.html")
@Theme(Lumo.class)
public class MyProjectUI extends UI { }

On line 1 you can see that we are referencing our myproject-theme.css file.

But you might also notice that we are using the .html file extension instead of .css. This is because of the auto-wrapping feature described below.

Supporting styling Shadow DOM with CSS auto-wrapping

If you just add a link to your CSS file (for example with the @Stylesheet annotation) you will only be able to style elements visible in the standand DOM.

Many of the Vaadin components today are leveraging something called a Shadow DOM which hides the element implementations from CSS.

To be able to also style the internals of the Vaadin components the DS Vaadin Flow Gradle Plugin will wrap any CSS file located in src/main/webapp/frontend/styles into the following HTML file:

myproject-theme.html (generated from myproject-theme.css)

1
2
3
4
5
6
7
<!-- This is a autogenerated html file for myproject-theme.css. Do not edit this file, it will be overwritten. -->
<custom-style>
    <style>
        label { color: green; }
        label.clicked { color: red; }
    </style>
</custom-style>

The convertion from CSS to HTML is done by the vaadinConvertStyleCssToHtml automatically whenever you are packaging your application so you don’t have to separately thing about running the task.

The final generated HTML wrappers are located in build/frontend/styles.