Home > Enterprise >  How can I use flexbox to make two items one center one bottom
How can I use flexbox to make two items one center one bottom

Time:12-20

https://i.stack.imgur.com/e2n5o.png

I want to achieve a layout like this by flexbox. body is flex container and there are only two flex items, one card and one footer. Here is a simplified codepen link. How can I make the footer at the bottom of the page while the card position center as it is now.

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;  
}

.container {  
  width: 400px;
  height: 300px;
  background-color: green;
}

.footer {  
  margin-bottom: 20px;
  background-color: yellow;
  width: 200px;
  height: 50px;
}
<div ></div>
<div ></div>

if I add margin-top:auto, the footer's position will be right, but the container will go to the top.

if I add gap to body, the container will not be at the center

CodePudding user response:

Use another element for the green card and make the .container fill all the available space using flex-grow: 1.

Use display: flex and align-items:center on the .container to center the card vertically.

body{
  display:flex;
  flex-direction:column;
  align-items:center;
  height:100vh;  
}

.container{  
  flex-grow: 1;
  display: flex;
  align-items: center;
}

.card {
  width:400px;
  height:300px;
  background-color:green;

}
.footer{  
  margin-bottom:20px;
  background-color:yellow;
  width: 200px;
  height:50px;
}
<div >
  <div ></div>
</div>
<div ></div>


The body does not need justify-content:center; so you should remove it too.

CodePudding user response:

You can use grid to center the container, and position to stick the footer.

body {
  display: grid;
  place-content: center; /* center the container */
  height: 100vh;
  margin: 0;
}

.container {
  width: 400px;
  height: 300px;
  background-color: green;
}

.footer {
  justify-self: center; /* center the footer */
  margin-bottom: 20px;
  background-color: yellow;
  width: 200px;
  height: 50px;
  
  /* push the footer to the bottom */
  position: sticky; 
  top: 100vh;
}
<div ></div>
<div ></div>

  • Related