如何让带标题的按钮并排且居中对齐?(前端初学)
实现带标题按钮组的并排居中效果
你刚学前端没几天,想要让带上方标题的按钮组实现并排且居中的效果,用CSS Flexbox就能轻松搞定,直接在现有HTML基础上添加以下CSS代码即可:
/* 让顶部标题居中显示 */ .section-title { text-align: center; margin-bottom: 20px; /* 可选:增加标题和按钮组的间距,让布局更宽松 */ } /* 按钮组容器启用弹性布局,实现子元素并排+整体居中 */ .buttons { display: flex; justify-content: center; /* 让两个按钮组在水平方向居中 */ gap: 40px; /* 控制两个按钮组之间的间距,可按需调整 */ } /* 让每个按钮组内部的标题和按钮居中对齐 */ .button-default, .button-hovered { text-align: center; } /* 可选:给按钮添加基础样式,让效果更贴近你的期望 */ button { margin: 0 6px; /* 按钮之间的小间距 */ padding: 8px 18px; border: none; border-radius: 4px; cursor: pointer; color: #fff; } .button-default button:first-of-type { background-color: #0078d4; } .button-default button:last-of-type { background-color: #6a737d; } .button-hovered button:first-of-type { background-color: #005a9e; } .button-hovered button:last-of-type { background-color: #545c66; }
关键代码解释:
.section-title设置text-align: center,让顶部标题居中显示;.buttons容器启用display: flex弹性布局,justify-content: center实现两个按钮组整体水平居中,gap控制组间间距;.button-default和.button-hovered设置text-align: center,确保组内的小标题和按钮居中对齐;- 最后的按钮样式为可选配置,可根据需求调整颜色、边距等样式参数。
内容的提问来源于stack exchange,提问作者Jeshua
相关产品推荐
相关产品推荐

