如何在 Vaadin TextField 中居中对齐文本

How to center align the text in Vaadin TextField

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

我尝试从组件中检索 elementt 然后检索 shadowRoot,然后从根检索 'input' 元素以向其添加样式,不幸的是这没有用,shadowroot 为 null(此代码从 onAttach 执行() 视图中的方法 class)

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。

您可以使用 CSS 来定位 value 部分:

.textfieldClass::part(value) {
  text-align: center;
}

此视频介绍样式 CSS 部分:https://youtu.be/Y0uxb4ga44Y

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

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