Bootstrap 4中input输入框设置居中不生效是什么原因?
问题原因
居中失效和Bootstrap版本无关,是两处代码错误导致的:
form-control类默认给input设置100%宽度,弹性布局下子元素占满父级时,justify-content:center的居中效果会被完全抵消,自然看不到居中表现- 你使用的
input-group-btn是Bootstrap 3的写法,同时输入框+按钮的组合没有套入Bootstrap 4要求的input-group外层容器,布局规则本身就不匹配。
修复后完整代码
<!DOCTYPE html> <html> <head> <title>HTML CSS JS</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div class="form-group"> <div class="d-flex justify-content-center"> <!-- 输入组外层容器,设置最大宽度避免占满整行 --> <div class="input-group" style="max-width: 500px;"> <input type="text" class="form-control" /> <!-- Bootstrap4 右侧按钮容器类 --> <div class="input-group-append"> <button class="btn btn-primary" type="button">Go!</button> </div> </div> </div> </div> </body> </html>
核心修改说明
- 输入框和按钮外层增加
input-group容器,符合Bootstrap4输入组组件的结构要求 - 把旧版的
input-group-btn替换为Bootstrap4规范的input-group-append类,适配按钮在输入框右侧的布局样式 - 给
input-group设置自定义最大宽度,避免输入组默认占满整行,让居中效果可以正常显示
内容的提问来源于stack exchange,提问作者user17074809
相关产品推荐
相关产品推荐

