如何实现Banner标题居左、图标居右布局(HTML/CSS)

我需要实现Banner中Title显示在最左侧,图标显示在最右侧,当前代码如下:
<div className={classNames.root} role="banner"> <div className={classNames.left}> Title </div> <div className={classNames.right}><SettingsIcon /></div> </div> root: [ { backgroundColor: theme.palette.themePrimary, height: 40, color: 'white', maxWidth: "100%", margin: '0 auto', borderBottom: '1px solid transparent', boxSizing: 'border-box', display: 'flex', paddingLeft: 20, paddingTop: 10 }, className ], left: { float: 'left' }, right: { fontSize: 20, float: 'right' }
修正方案:
你已经给根容器设置了display: flex,但float属性在flex布局中不会生效,需要用flex的原生布局属性来实现两端对齐:
- 给根容器样式添加
justifyContent: 'space-between',让左右元素分别靠向容器两端;同时添加alignItems: 'center',让标题和图标垂直居中,此时可以去掉paddingTop避免内容位置偏移。 - 移除
left和right类中的float属性,给right类添加marginRight: 20,和左侧的paddingLeft保持一致间距。
修正后的代码如下:
<div className={classNames.root} role="banner"> <div className={classNames.left}> Title </div> <div className={classNames.right}><SettingsIcon /></div> </div> root: [ { backgroundColor: theme.palette.themePrimary, height: 40, color: 'white', maxWidth: "100%", margin: '0 auto', borderBottom: '1px solid transparent', boxSizing: 'border-box', display: 'flex', paddingLeft: 20, justifyContent: 'space-between', // 实现两端对齐 alignItems: 'center' // 实现垂直居中 }, className ], left: { // 移除float属性 }, right: { fontSize: 20, marginRight: 20 // 添加右侧间距 }
这样就能实现标题居左、图标居右的预期布局效果。
内容的提问来源于stack exchange,提问作者user989988
相关产品推荐
相关产品推荐

