如何在VaadinTextField中居中对齐文本

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

我尝试从组件中检索 elementt,然后检索 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。

回答

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

centerTextField.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER);

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


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


以上是如何在VaadinTextField中居中对齐文本的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>