我有一个简单的内联表单。
<form>
<span>Signup to our list!</span>
<input type="email" placeholder="your email address">
<input type="submit" value="Subscribe">
</form>
我想使用 flexbox 来均匀地分隔元素。然后当屏幕尺寸太小时,将元素包装到它们自己的行中,居中。
我从这里开始:http://codepen.io/magician11/pen/PPvVRv
目前的问题是:
- 他们不会换行,
- 元素之间没有间距,
- 我不确定如何让元素在换行时居中
最佳答案
您演示中的这行代码...
input[type="email"] {
flex: 2 0 18rem;
}
... 告诉 input
元素拉伸(stretch)容器的整个可用宽度。因此,当发生这种情况时,该行上就没有剩余空间,并且您的三个元素排在一起,中间没有空间。
有几种方法可以更改此行为以在元素之间创建空间。一种简单的方法是从上面的代码中删除 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; }
}
更新(基于评论)
When it wraps, how do I create vertical space between the elements?
一种简单的方法是在 flex 元素之间应用 margin
。
@media screen and ( max-width: 1000px ) {
form { justify-content: center; }
form > * { margin-bottom: 15px; }
}
关于html - 如何使用 flexbox 创建响应式表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908717/