Using CSS layouts for mobile devices
Another nice feature of the CSS layout is that components are wrapped when they reach the width of the layout. This feature can be used to create layouts for small displays, for example, mobile phones or some tablets. We will create a simple layout with a header, two menus, and content in the middle of them.
As we can see in the following screenshot, if the user opens our application on a wide screen, components are displayed side by side. Except the header that takes up the whole width of the page.
If the user opens our application on a narrow screen, for example, on a mobile device, then all components will be aligned into the one column.
How to do it...
Carry out the following steps to create an application with a flexible layout for mobile devices:
- Create a project with the main UI class called, for example,
Demo
.public class Demo extends UI {…}
- We create a
MobileLayout
class that extendsCssLayout
.public class MobileLayout extends CssLayout {…}
- At first we create a constant with Lorem Ipsum text.
private static final String LIPSUM = "Lorem ipsum dolor sit amet, consectetur adipisicing elit.";
- The key functionality is in the constructor. Here we create all the sections of the layout. On the top of the page we put the header. On the left and right sides we insert menus. In the middle will be the content of the page.
public MobileLayout() { Label header = new Label("<h1>CSS layout</h1>", ContentMode.HTML); addComponent(header); addComponent(createMenu()); Label content = new Label(LIPSUM); content.setWidth(70, Unit.PERCENTAGE); addComponent(content); addComponent(createMenu()); }
- For a better look, we set a margin around all components. We also align them vertically upwards. As in the previous recipe, we can do it by overriding the
getCss()
method.@Override protected String getCss(Component c) { return "margin: 5px; vertical-align: top;"; }
- Implementation of the
createMenu()
method is the same as in the Creating an adjustable layout using split panels recipe of this chapter.private Tree createMenu() {…}
- That's all. Now we can use or create
MobileLayout
in the main UI class calledDemo
.public class Demo extends UI { @Override protected void init(VaadinRequest request) { setContent(new MobileLayout()); } }
We can run the server and open the application in the web browser.
How it works...
All the components in the CssLayout
class are inserted horizontally and wrapped when they reach the width of the layout. Except the header that takes up the whole width of the page, because Label
has a default setting of 100
percent width.
CssLayout
has a very simple Document Object Model (DOM) structure. It's the fastest of the layout components.
See also
- The Controlling components over the CSS layout recipe