How to create a wrapping HorizontalLayout

Today I wanted to create a layout like the HorizontalLayout, except that I wanted it to wrap.
When I googled this, I saw hints that a CssLayout was the way to go, but I found no concrete examples.

It is possible that this is common knowledge in the community, but in case there are others that are struggling with the same, here is how I solved it:

What stumped me was that the fields and their labels in a CssLayout are just a flat list of

s.
It is possible that there is some css magic that can group these together in pairs and render them the way I want, but that was beyond me.

What I wanted was a parent

around the label+field pairs, just like in a regular HorizontalLayout.

It finally dawned on me that a CssLayout
is
more or less only a

, so I could create the “v-slot” myself by wrapping each field in an extra CssLayout.

This worked like a charm.

CssLayout wrappingLayout = new CssLayout();
<parent>.addComponent(wrappingLayout);
wrappingLayout.setStyleName("wrap");

for(int i=0; i<20; i++) {
	
	CssLayout slot = new CssLayout();
	slot.setPrimaryStyleName("v-slot");
	wrappingLayout.addComponent(slot);
	
	Field f = new TextField("Textfield no " + i);
	slot.addComponent(f);

}

And in my css, just to get some space between each slot:

  .v-csslayout-wrap > .v-slot {
    margin-right: 8px;
  } 

Might make for a nice, simple addon for others with similar needs, if you extended CssLayout to do that for every added component :slight_smile:

I did think about creating a subclass of CssLayout, but I thought it would be a bad idea to (just) override addComponent to add a wrapper-layout around the component. That would for instance mean that getComponent(int) would return the wrapper component instead of the actual component that was added.

To create a workable subclass I assume I would have to add the v-slot div in the client-side part of the Layout, and, frankly, I’m not ready for that yet. Also, it seemed too much work to save just a few lines of code.