关于layout 布局 内容高度不填充问题

662 阅读1分钟

问题背景

最近接手了一个研究院的数据库项目,因此迫切的选用了最新版本的Vite + Ts + React 进行开发,在项目的基本搭建时,整体选用了Ant-Design UI库的Layout组件进行排版布局。在Content组件中渲染Route时,发现给内部设置height:100% 没有生效,单独设置高度会生效。但是外层的元素是撑开的。

问题复现

<Layout style={{ minHeight: '100vh' }}>
    <Header>
        <Menu selectable={true} mode="horizontal" theme="dark" items={routerConfig} />
    </Header>
    <Content style={{ margin: '5px 16px 0 16px' }}>
        <div style={{ width: '100%' }}>
            ...
        </div>
    </Content>
    <Footer />
</Layout>

image.png

image.png

自己的处理方式

再尝试中发现,给内部元素设置固定高是会生效,因此自己的处理方式是计算出Contet组件的高度,然后给内部元素设置高度。

来自 Stack overflow的方法

给Content组件添加display: flex; align-items: stretch的样式属性,再给内部组件元素设置width: 100%就可以了

<Content style={{ margin: '5px 16px 0 16px', display: 'flex', alignItems: 'stretch' }}>
    <div style={{ width: '100%' }}>
        <Routes>
            {
                flatRouterConfig.map((item) => {
                    return <Route
                        key={item.key}
                        path={item.path}
                        element={ item.component }
                    />
                })
            }
        </Routes>
    </div>
</Content>

解释

align-items: stretch 设置是将flex布局中的子元素 按照交叉轴方向进行拉伸,即在交叉轴方向与父元素保持一致的长度。