fredericmarcel
fredericmarcel

Reputation: 73

Vertically align a flexbox

There are three buttons (button 1, button 2 and button 3) in a flexbox (myflex).

How can I put this flexbox at the bottom of the screen and center it horizontally?

I can center it, but not put it at the bottom of the screen and make it a sticky footer.

#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>

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

Upvotes: 0

Views: 207

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 370993

In order to move an element vertically, the container must have extra height.

Unlike width, which block elements fill 100% by default, heights must be defined. Otherwise, elements default to auto – the height of the content.

In your code, there is no height specified, so your flex container has no extra space for alignment. For an illustration, set borders around the body element and your container:

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

#myflex {
  display: flex;
  bottom: 20px;
  justify-content: center;
  border: 1px solid red;
}
<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>

Once you have the height issue resolved, you can use flex keyword properties or auto margins to center-align the flex container at the bottom.

Method 1: Flex Keyword Properties

body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
<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>

Method 2: Flex Auto Margins

body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
}
#myflex {
  margin-top: auto;
}
<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>

OR, if you want the footer to remain fixed on the screen, try this:

Method 3: Fixed Positioning

body {
  height: 100vh;
  margin: 0;
}
#myflex {
  position: fixed;
  display: flex;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}
<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>


Upvotes: 1

Related Questions