HTML与CSS:如何让两个行内表单按钮水平居中
解决方案
你遇到的问题是属性位置加错、flex属性配置错误两个原因导致的,按以下步骤修改即可:
- 修正
body的flex配置:你写的align-items: column是无效值,align-items用于控制交叉轴元素对齐,要让body内的nav、form垂直排列,需要设置flex-direction: column - 给按钮的父容器添加对齐属性:你之前给
.buttons加的text-align: center只会控制按钮内部的文字居中,不会控制按钮本身的位置。两个按钮属于行内块元素,给它们的直接父容器form.search设置text-align: center即可让按钮在父容器内水平居中。
修改后的CSS代码
* { font-family: arial, sans-serif; margin: 0; padding: 0; box-sizing: border-box; } body { display: flex; /* 替换错误属性,设置子元素垂直排列 */ flex-direction: column; /* 可选:如果需要内容整体在页面垂直居中,可调整justify-content的值为center */ min-height: 100vh; justify-content: flex-start; } /* 新增form的样式 */ form.search { text-align: center; width: 100%; max-width: 584px; margin: 50px auto 0; } .buttons { background-color: #f8f9fa; border: 1px solid #f8f9fa; border-radius: 4px; font-size: 14px; margin: 11px 4px; padding: 0 16px; line-height: 27px; height: 36px; min-width: 54px; text-align: center; cursor: pointer; user-select: none; display: inline-block; } .search_area { color: rgba(0, 0, 0, .87); border: 1px solid #ddd; width: 100%; height: 34px; font-size: 16px; border-radius: 25px; padding: 0 16px; } nav { display: flex; justify-content: flex-end; gap: 20px; margin-right: 30px; margin-top: 15px; }
HTML代码不需要做任何修改,修改CSS后即可实现两个按钮水平居中的效果。
内容的提问来源于stack exchange,提问作者equanimity
相关产品推荐
相关产品推荐

