如何在Semantic Grid行中水平居中内容(无需空列标签实现)
嘿,你现在用空列实现居中的思路没问题,但确实有更优雅的方式,不用额外添加空标签,下面给你两种实用的方案:
方案1:利用Semantic UI Grid的offset属性(推荐)
Semantic UI的Grid Column自带offset属性,可以直接设置列的偏移量,完美替代你用空列占位的方式。因为你左侧固定是2列,中间内容列是8列,剩下的16-2-8=6列需要平均分配到左右(各3列),所以给中间内容列设置对应设备的offset值即可:
<Grid style={{ height: "100vh"}} padded> <Grid.Row> {/* 左侧侧边栏 */} <Grid.Column tablet={2} computer={2} stretched> <Main activePage={"Add Department"} /> </Grid.Column> {/* 中间内容列,添加offset属性替代空列 */} <Grid.Column tablet={{ width: 8, offset: 3 }} computer={{ width: 8, offset: 3 }} verticalAlign={"middle"} > <Header as={"h2"} textAlign={"center"}> Department </Header> <Divider section /> <Form> <FormInput headerText={"Name"} onChange={value => { value != "" ? setFormErrors(false) : setFormErrors(true); // 修复语法错误,添加分号 setDepartmentName(value); }} /> </Form> <Divider section /> <Button color={"blue"} fluid size={"large"} onClick={SaveForm}> Save </Button> {Messages()} </Grid.Column> </Grid.Row> </Grid>
原理:offset会自动在当前列的左侧添加指定列数的空白占位,这样就不用手动写空的Grid.Column了,代码更简洁易维护。
方案2:使用Flex布局自定义对齐
如果需要更灵活的布局控制,可以利用Semantic UI Grid本身基于Flex的特性,给Grid.Row添加自定义样式来实现内容居中:
<Grid style={{ height: "100vh"}} padded> <Grid.Row style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}> {/* 左侧侧边栏 */} <Grid.Column tablet={2} computer={2} stretched> <Main activePage={"Add Department"} /> </Grid.Column> {/* 中间内容列,设置固定宽度 */} <Grid.Column tablet={8} computer={8} verticalAlign={"middle"}> <Header as={"h2"} textAlign={"center"}> Department </Header> <Divider section /> <Form> <FormInput headerText={"Name"} onChange={value => { value != "" ? setFormErrors(false) : setFormErrors(true); setDepartmentName(value); }} /> </Form> <Divider section /> <Button color={"blue"} fluid size={"large"} onClick={SaveForm}> Save </Button> {Messages()} </Grid.Column> {/* 右侧占位列,利用flex自动分配空间 */} <Grid.Column tablet={6} computer={6} /> </Grid.Row> </Grid>
不过这种方式需要手动计算剩余列数,不如方案1直观,所以更推荐用offset属性的方式。
另外,注意你原来的onChange回调里有个小语法错误,已经在示例里修复了(setFormErrors(true)后面加了分号),避免运行时出错~
内容的提问来源于stack exchange,提问作者dev00001
相关产品推荐
相关产品推荐

