rmuller
rmuller

Reputation: 12849

How set the label width of a FormLayout in Vaadin Flow?

Using Vaadin 12 with FormLayout and labels left of input fields.

I want to set the width of the label column. How to achieve this, using the Java API?

Upvotes: 5

Views: 3259

Answers (2)

Tatu Lund
Tatu Lund

Reputation: 10623

If you are using FormItem.addToLabel(..) method to set the label content, then the width of that is controlled in FormItem by custom property --vaadin-form-item-label-width (see more: https://vaadin.com/components/vaadin-form-layout/html-api/elements/Vaadin.FormItemElement ) The default value is 8em. So you can set is wider e.g. with:

formItem.getElement().getStyle().set("--vaadin-form-item-label-width", "10em");

You cannot create instance of FormItem directly but it is returned when adding component to FormLayout:

FormItem formItem = formlayout.addFormItem(component, "label text");

Upvotes: 6

rmuller
rmuller

Reputation: 12849

For setting the individual FormItem label width and/or a more dynamic approach, see both answer @TatuLund and his comment for this solution.

For setting the label with in the whole Form, use @HtmlImport("frontend://styles/shared-styles.html")

And in shared-styles.html add this fragment:

<dom-module theme-for="vaadin-form-item" id="custom-form-item">
    <template>
        <style>     
            :host {
                --vaadin-form-item-label-width: 15em;  
            }
        </style>
    </template>
</dom-module>

Gotcha (for me): theme-for="vaadin-form-item" instead of theme-for="vaadin-form-layout"



UPDATE for Vaadin Flow v14+ (tested with v14.1.3)

Create form-item.css in PROJECT_DIR/frontend/styles/ with content:

   :host {
        --vaadin-form-item-label-width: 15em;
    }

Add annotation in top-level routing class (in my case the master layout class):

@CssImport(value = "./styles/form-item.css", themeFor = "vaadin-form-item")

Also see https://vaadin.com/docs/v14/flow/theme/migrate-p2-to-p3.html and https://stackoverflow.com/a/57553974/868941.

Upvotes: 3

Related Questions