如何使用 flexbox 创建响应式表单?

How do I create a responsive form using flexbox?

我有一个简单的内联表单。

<form>
 <span>Signup to our list!</span>
 <input type="email" placeholder="your email address">
 <input type="submit" value="Subscribe">
</form>

我想使用 flexbox 来均匀 space 出元素。然后当屏幕尺寸太小时,将元素包装到它们自己的行中,居中。

我从这里开始:http://codepen.io/magician11/pen/PPvVRv

目前的问题是:

这适合你吗? JSfiddle
刚刚删除 flex-shrinkflex-grow 输入。

您演示中的这行代码...

input[type="email"] {
  flex: 2 0 18rem;
}

... 告诉 input 元素拉伸容器的整个可用宽度。因此,当发生这种情况时,该行上没有 space,并且您的三个项目排在一起,中间没有 space。

有几种方法可以改变此行为以在元素之间创建 space。一种简单的方法是从上面的代码中删除 flex-grow: 2 因素。试试这个:

input[type="email"] {
  flex: 0 1 60rem; /* don't grow, shrink proportionally, start at 60rem width */
}

对于要包装的项目,您需要允许容器增加高度,以便它可以容纳新的项目行:

form {
  padding: 1rem;
  border-radius: 8px;
  background-color: orange;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  min-height: 30px; /* new; value for demo purposes only */
}

要使项目在包装上居中,您可以使用媒体查询:

@media screen and ( max-width: 1000px ) {
  form { justify-content: center; }
}

DEMO


更新(基于评论)

When it wraps, how do I create vertical space between the elements?

一种简单的方法是在弹性项目之间应用 margin

@media screen and ( max-width: 1000px ) {
     form { justify-content: center; }
     form > * { margin-bottom: 15px; }
}

DEMO

解决方案http://codepen.io/gmrash/pen/KdLOZJ

<form>
  <span>Signup to our list!</span>
  <input type="email" placeholder="your email address">
  <input type="submit" value="Subscribe">
</form>

form {
  padding: 1rem;
  border-radius: 8px;
  background-color: orange;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

span {
  flex: 0 0 8rem;
  margin-right: 10px;
}

input[type="email"] {
  flex: 2 1 18rem;
}

input[type="submit"] {
  flex: 0 0 8rem;
  margin-left: 10px;
}