【问题标题】:How to center align the text in Vaadin TextField如何居中对齐 Vaadin TextField 中的文本
【发布时间】:2021-05-06 00:45:42
【问题描述】:

我阅读了 CSS 样式部分 (https://vaadin.com/docs/v14/flow/styling/styling-components),它提到全局 CSS 不会影响 shadow DOM 中的“INPUT”字段,因此必须将样式添加到 shdaow DOM,但不幸的是它没有明确说明如何将样式添加到 shadow 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


    【解决方案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

    【讨论】:

    【解决方案2】:

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

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

    这个视频解释了 CSS 部分的样式:https://youtu.be/Y0uxb4ga44Y

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2013-10-02
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多