Nat_Pat
Nat_Pat

Reputation: 21

How to force a flex item to the bottom of the page?

This is how I want my Layout

Desired Layout1

Currently it looks like this Current layout

I can increase the size of the second box by specifying the height.

.row-2 {
  height: 500px;
}

Surely there is a better way than this.

I've also tried to force the last row of boxes to the bottom without any luck:

.row-3 {
  margin-top: auto;
}

My flexbox is as follows:

<div className="container">
  <div className="row-1">1</div>
  <div className="row-2">2</div>
  <div className="row-3">
    <div>3</div>
    <div>4</div>
  </div>
</div>
.container {
  display: flex;
  flex-direction: column;
  max-width: 100%;
}

.row-1 {
  border: 2px solid green;
}

.row-2 {
  border: 2px solid blue;
}

.row-3 {
  border: 2px solid red;
  display: flex;
  flex: 1;
  margin-top: auto; /* not working */
}

.row-3 > div {
  flex-grow: 1;
  border: 2px solid purple;
}

Upvotes: 1

Views: 59

Answers (2)

Prathamesh Koshti
Prathamesh Koshti

Reputation: 1360

I am suspecting that your container is the immediate child of the <body>. If so, body will have height as much as it has to hold, in this case it will have the height same as the container. Because of this you are not able to do what you really want.

I would recommend you to add min-height: 100vh to the container, this will create the container of height 100% of the viewport.

.container {
  min-height: 100vh
}

And your rest of the code will do the job.

Upvotes: 0

Sam
Sam

Reputation: 2351

Having flex-grow: 1; is probably a problem. I think that you're specifically saying that the third row can grow more. You might want to delete that and set flex-grow: 2; on the second row.


Maybe set width: 100%; on the second row?


It does look like you should use css-grid instead though. I'd recommend this tutorial for learning it

Upvotes: 1

Related Questions