垂直分布divs

4
如何垂直均匀分布子元素?例如,如果我有一个包含3个输入字段的div,每个字段设置为100%宽度,我希望它们在三行中均匀分布,即高度为33.33%,如图片所示。此外,如果有2个字段,我希望它们分别在两行中均匀分布,每行高度为50%,而无需明确设置。有任何想法吗? enter image description here 目前,我的代码将所有输入字段堆叠在顶部,如下面的片段所示。

input { width: 60%;}
.whole-container { height: 300px;background: yellow;}
<body>
  <div class="whole-container">
    <form id="login-form" method="POST">
      <input name="name" type="text" placeholder="Your name" id="cf-nameInput">
      <input name="email" type="email" placeholder="your@email" id="cf-emailInput">
      <input name="tel" type="tel" placeholder="Phone number" id="cf-phoneInput">
    </form>
  </div>
</body>


如果任何答案回答了您的问题,请接受它,这将有助于其他人。 - Mosh Feu
3个回答

3
你可以使用flex:

input { 
  width: 60%;
}

.whole-container { 
  height: 300px;
  background: yellow;
}

.whole-container form {
  height:100%;
  display:flex;
  flex-direction:column;
  justify-content:space-around;
}
<body>
  <div class="whole-container">
    <form id="login-form" method="POST">
      <div><input name="name" type="text" placeholder="Your name" id="cf-nameInput"></div>
      <div><input name="email" type="email" placeholder="your@email" id="cf-emailInput"></div>
      <div><input name="tel" type="tel" placeholder="Phone number" id="cf-phoneInput"></div>
    </form>
  </div>
</body>


2

Flex可以帮助你:

form {height:300px;
  display:flex;
  flex-flow:column;
  justify-content:space-around;
  background:yellow;
  }
input {
 width: 60%;}
<div class="whole-container">
  <form id="login-form" method="POST">
            <input name="name" type="text" placeholder="Your name" id="cf-nameInput">
            <input name="email" type="email" placeholder="your@email" id="cf-emailInput">
            <input name="tel" type="tel" placeholder="Phone number" id="cf-phoneInput">
  </form>
  </div>


1
如果您想使用不涉及 display:flex 的解决方案,可以查看以下示例:

input { width: 60%;}
#login-form { height:100%; }
.whole-container { display:block; height: 300px;background: yellow;}
.container { min-height:33%; }
<div class="whole-container">
  <form id="login-form" method="POST">
            <div class="container">
            <input name="name" type="text" placeholder="Your name" id="cf-nameInput">
            </div>
            <div class="container">
            <input name="email" type="email" placeholder="your@email" id="cf-emailInput">
            </div>
            <div class="container">
            <input name="tel" type="tel" placeholder="Phone number" id="cf-phoneInput">
            </div>
  </form>
</div>

这基本上只是将 input 包装在一个 div 中,然后根据所需的输入量(在此情况下为 33%)分配 div 的高度。


这将第一个输入放在顶边,而作者希望它与顶边有一定的间距。我猜想输入应该在div内额外垂直居中。 - Ruslan Bes
他可以使用一些额外的CSS来定位输入框,例如在输入框中添加position:absolute; bottom:0; CSS将使所有输入框对齐到底部,如果他想要在容器内垂直对齐它们也是同样的方法。我提供了这个例子,因为如果有人需要支持旧浏览器,display:flex就不起作用了。 - LS_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接