首页 > 解决方案 > 如何居中对齐 Vaadin TextField 中的文本

问题描述

我阅读了 CSS 样式部分(https://vaadin.com/docs/v14/flow/styling/styling-components),它提到全局 CSS 不会影响影子 DOM 中的“输入”字段,所以样式必须是添加到 shdaow DOM,但不幸的是,它没有明确说明如何将样式添加到影子 DOM。注意。我主要使用 Flow 纯 java 和一点 CSS。

我尝试从组件中检索元素,然后检索 shadowRoot,然后从根中检索“输入”元素以向其添加样式,不幸的是,这不起作用,shadowroot 为空(此代码从视图类中的 onAttach() 方法执行)

private void setTextAlignCenterForTextFields(TextField textField) {
        //find the internal 'Input' and set the styling to text-align=center, unfortunately
        // you cant do that with global css, since the 'input' element is in shadow root
        textField.getElement()
                .getShadowRoot()
                .get()
                .getChildren()
                .filter( elem -> "INPUT".equalsIgnoreCase(elem.getTag()))
                .forEach(inputElem -> inputElem.getStyle().set("text-align", "center"));
    }

任何想法,将不胜感激。我正在使用 Vaadin 版本 14.5.1。

标签: vaadin

解决方案


已经有一个主题变体来对齐文本

centerTextField.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER);

https://vaadin.com/components/vaadin-text-field/java-examples/theme-variants


至于如何将 CSS 附加到阴影根,基本上使用themeFor,请参阅https://vaadin.com/docs/v14/flow/styling/importing-style-sheets/#component-styles


推荐阅读