垂直分配div

时间:2016-06-20 12:55:28

标签: html css

如何垂直均匀地分发子元素?例如,如果我有一个带有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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分: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 :(得分:1)

您可以使用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 :(得分:1)

如果您想要一个不使用display:flex的解决方案,可以查看以下示例:

&#13;
&#13;
input { width: 60%;}
#login-form { height:100%; }
.whole-container { display:block; height: 300px;background: yellow;}
.container { min-height:33%; }
&#13;
<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>
&#13;
&#13;
&#13;

这基本上只是将input包裹在div内,然后根据您需要的输入量(在这种情况下为33%)指定div的高度