You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flex布局中input[type=number]与input[type=checkbox]对齐问题

如何让flex容器中的input[type=number]与复选框垂直对齐?

当前input[type=number]位于flex容器的右上角,但换成input[type=checkbox]时能正常对齐,请问怎么设置才能让数字输入框和其他复选框保持对齐?

原始代码示例

CSS

body {
  background-color : #6d6875;
  font-family      : 'Open Sans', sans-serif;
}
#options-div {
  background-color : #b5838d;
  margin           : 200px auto;
  padding          : 20px;
  width            : 350px;
  text-align       : center;
  border           : 2px solid white;
}
#password-output {
  width  : 200px;
}
#num-box {
  width  : 30px;
  height : 30px;
}
.options {
  display         : flex;
  justify-content : space-between;
  border          : 2px solid black;
}

HTML

<div id="options-div">
  <h1>Password generator</h1>
  <input id="password-output" type="number">
  <div class="options">
    <p>Password length</p>
    <input id="num-box" type="number">
  </div>
  <div class="options">
    <p>Include uppercase letters</p>
    <input type="checkbox">
  </div>
</div>

解决方案

问题根源在于flex容器默认的align-items属性值是stretch,会让子元素拉伸至容器高度,但不同类型的input元素默认垂直表现有差异,导致数字输入框和复选框不对齐。

最直接的解决方法是给.options容器添加align-items: center,统一让所有子元素在垂直方向居中对齐:

.options {
  display         : flex;
  justify-content : space-between;
  align-items     : center; /* 添加这一行 */
  border          : 2px solid black;
}

如果不想修改flex容器属性,也可以单独给数字输入框设置垂直对齐:

#num-box {
  width            : 30px;
  height           : 30px;
  vertical-align   : middle; /* 添加这一行 */
}

两种方法都能实现对齐效果,推荐第一种,它能统一容器内所有子元素的对齐规则,避免后续新增元素时重复调整。

内容的提问来源于stack exchange,提问作者zampoan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:22:46