垂直对齐flexbox

时间:2016-04-04 14:04:51

标签: html css css3 flexbox

flexbox(myflex)中有三个按钮(按钮1,按钮2和按钮3)。

如何将此弹性框放在屏幕底部并将其水平居中?

我可以将它居中,但不要把它放在屏幕的底部并使其成为粘性页脚。



#myflex {
  display: flex;
  //position:fixed;
  bottom: 20px;
  justify-content: center;
  bottom: 10px;
}

<div id="myflex">
  <button class="button button1">button 1</button>
  <button class="button button2">button 2</button>
  <button class="button button3">button 33</button>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/fredericmarcel/7ssq32te/3/

1 个答案:

答案 0 :(得分:1)

为了垂直移动元素,容器必须具有额外的高度。

与宽度不同,默认情况下哪个块元素填充100%,必须定义高度。否则,元素默认为auto - 内容的高度。

在您的代码中,没有指定高度,因此您的Flex容器没有额外的对齐空间。要进行说明,请在body元素和容器周围设置边框:

&#13;
&#13;
body {
  border: 2px dashed red;
  padding: 1px;
}

#myflex {
  display: flex;
  bottom: 20px;
  justify-content: center;
  border: 1px solid red;
}
&#13;
<div id="myflex">
  <button class="button button1">button 1</button>
  <button class="button button2">button 2</button>
  <button class="button button3">button 33</button>
</div>
&#13;
&#13;
&#13;

解决高度问题后,您可以使用flex关键字属性或auto margins将Flex容器居中对齐。

方法1:Flex关键字属性

&#13;
&#13;
body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
&#13;
<div id="myflex">
  <button class="button button1">button 1</button>
  <button class="button button2">button 2</button>
  <button class="button button3">button 33</button>
</div>
&#13;
&#13;
&#13;

方法2:弹性自动边距

&#13;
&#13;
body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
}
#myflex {
  margin-top: auto;
}
&#13;
<div id="myflex">
  <button class="button button1">button 1</button>
  <button class="button button2">button 2</button>
  <button class="button button3">button 33</button>
</div>
&#13;
&#13;
&#13;

或者,如果您希望页脚在屏幕上保持固定,请尝试:

方法3:固定定位

&#13;
&#13;
body {
  height: 100vh;
  margin: 0;
}
#myflex {
  position: fixed;
  display: flex;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}
&#13;
<div id="myflex">
  <button class="button button1">button 1</button>
  <button class="button button2">button 2</button>
  <button class="button button3">button 33</button>
</div>
&#13;
&#13;
&#13;