Line Break in Span Element or Text

Hi. I wanted to make a Span tag and added text. But it wasnt auto breaking lines. I dont want text area because its more of a bigger label than an input field. Any advice on this? Text doesnt break either. Thanks in advance

Guess I will stick with label.

Depends where and for what you need the line break. Inside an Input fields’ caption or for example to break apart Paragraphs.

I’m not 100% sure what you are looking for but to me Span is “auto breaking” just fine. My guess is you mean that line breaks are preserved, which is a “web thing”. Maybe one of these examples will help:

        setWidth("100px");
        String text = "foo\nbar\nloooongngngnll line that should autobreak";
        
        add(new Paragraph(text));
        add(new Span(text));
        add(new Pre(text));
        add(new ParagraphWithLineBreaks(text));

The implementation for the last one:

    /**
     * Use this class if you want line breaks to be maintained for text and also
     * automatically break line when needed.
     */
    public static class ParagraphWithLineBreaks extends Paragraph {

        public ParagraphWithLineBreaks(String textWithLineBreaks) {
            setText(textWithLineBreaks);
            maintainLineBreaks();
        }

        private void maintainLineBreaks() {
             // use `pre` if you want manual line breaks only
            getStyle().set("white-space", "pre-line");
        }
    }


This is how those render.

Span and many other html element classes have dedicated APIs for setting the white-space behavior, e.g.
span.setWhiteSpace(WhiteSpace.PRE);

Label should only be used for custom labels of fields etc – it’s not a generic text element.

Thanks for your advices. Will test it tomorrow.