在 Vaadin Flow 的布局中居中小部件

Center widgets within a layout in Vaadin Flow

当另一个布局中的 LoginLayout 等小部件出现在更大的 window 中时,如何使内容居中?我希望内容在宽度和高度方面大约出现在 window 的中间。

我在 Flow(版本 10+,现在是 14)之前找到了关于此主题的较旧问题,例如 and , but they are for the previous generation of Vaadin(版本 6、7、8)。

HorizontalLayout 与 CSS3 Flexbox

值得信赖的HorizontalLayout and VerticalLayout classes from olden days are still in Vaadin 14. This pair of classes have been retrofitted to use modern Flexbox technology found in CSS3. See excellent tutorials on Flexbox at CSS-Tricks.com and at Mozilla。 CSS3 Flexbox 在概念上非常 接近 classic Vaadin HorizontalLayoutVerticalLayout 的行为。

在下面的示例中,我们从 Vaadin HorizontalLayout 开始。

final public class AuthenticateView extends HorizontalLayout

在构造函数中,将您的小部件添加到布局中,LoginForm 是本例中的小部件。

this.add ( new LoginForm() );

使 HorizontalLayout 使用所有可用的宽度和高度空间。

this.setSizeFull ();

将布局中的内容(我们的LoginForm)设置为横向移动到中间。这里的动词“justify”指的是typographer/designer lingo,其中justification 表示与页边距对齐。

this.setJustifyContentMode ( FlexComponent.JustifyContentMode.CENTER );

最后,我们可以指定我们的内容应该在我们现在非常高的布局中垂直显示的位置。我们想要内容在顶部、底部还是中间?

请注意此处与 Vaadin 8 代的语法差异:术语 FlexComponent 反映了 CSS Flexbox 的使用。

this.setDefaultVerticalComponentAlignment ( FlexComponent.Alignment.CENTER );

额外功能:让我们通过给不可见的边缘着色来直观地验证 HorizontalLayout 的行为。

this.getStyle ().set ( "border" , "6px dotted DarkOrange" );  // DEBUG - Visually display the  bounds of this layout.

通过 @Route 注释将此视图设置为默认视图。

@Route ( "" )
final public class AuthenticateView extends HorizontalLayout

当 运行 我们发现我们的登录表单出现在我们更大的网络浏览器 window 的中心位置。请注意橙色边框,显示我们的 HorizontalLayout 是如何增长到占据整个 window 的。

为了好玩,请尝试禁用此处显示的各行代码。 运行 应用程序通过注意 LoginForm 和橙色边框的位置来查看代码对行为的影响。

这是完整的 class 代码。

package work.basil.example.ui;

import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.login.LoginI18n;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.router.Route;

@Route ( "" )
final public class AuthenticateView extends HorizontalLayout
{
    // Constructor
    public AuthenticateView ( )
    {
        super ();

        // Widgets
        this.add ( new LoginForm () );

        // Arrange
        this.getStyle ().set ( "border" , "6px dotted DarkOrange" );  // DEBUG - Visually display the  bounds of this layout.
        this.setSizeFull ();
        this.setJustifyContentMode ( FlexComponent.JustifyContentMode.CENTER ); // Put content in the middle horizontally.
        this.setDefaultVerticalComponentAlignment ( FlexComponent.Alignment.CENTER ); // Put content in the middle vertically.

    }
}

警告:上面显示的这段代码对于现实世界的登录工作来说还远远不够。这里的重点是小部件布局,而不是用户身份验证。