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.
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.
To align the div content to the bottom, use position: relative to the container class and position: absolute to the div element.
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.
You can use auto margins
Prior to alignment via
justify-content
andalign-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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With