Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align an element to bottom with flexbox

Tags:

html

css

flexbox

I have a div with some children:

<div class="content">   <h1>heading 1</h1>   <h2>heading 2</h2>   <p>Some more or less text</p>   <a href="/" class="button">Click me</a> </div> 

and I want the following layout:

 ------------------- |heading 1          | |heading 2          |  |paragraph text     | |can have many      | |rows               | |                   | |                   | |                   |  |link-button        |  ------------------- 

Regardless how much text is in the p I want to stick the .button always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.

like image 396
supersize Avatar asked Jun 23 '15 10:06

supersize


People also ask

How do you put an element at the bottom of a div Flex?

A multi-row layout where we need to place an element to the bottom of its parent container can be created easily using CSS flex. The trick is to set margin-top: auto for the last element so that the top margin is automatically set as the per the remaining space left.

How do you align items at the bottom?

To align the div content to the bottom, use position: relative to the container class and position: absolute to the div element.

How do you position elements in Flex?

Justify ContentFlex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.


1 Answers

You can use auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

So you can use one of these (or both):

p { margin-bottom: auto; } /* Push following elements to the bottom */ a { margin-top: auto; } /* Push it and following elements to the bottom */ 

.content {    height: 200px;    border: 1px solid;    display: flex;    flex-direction: column;  }  h1, h2 {    margin: 0;  }  a {    margin-top: auto;  }
<div class="content">    <h1>heading 1</h1>    <h2>heading 2</h2>    <p>Some text more or less</p>    <a href="/" class="button">Click me</a>  </div>

Alternatively, you can make the element before the a grow to fill the available space:

p { flex-grow: 1; } /* Grow to fill available space */ 

.content {    height: 200px;    border: 1px solid;    display: flex;    flex-direction: column;  }  h1, h2 {    margin: 0;  }  p {    flex-grow: 1;  }
<div class="content">    <h1>heading 1</h1>    <h2>heading 2</h2>    <p>Some text more or less</p>    <a href="/" class="button">Click me</a>  </div>
like image 188
Oriol Avatar answered Dec 04 '22 04:12

Oriol