"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Align Elements to the Bottom of a Container Using Flexbox?

How Can I Align Elements to the Bottom of a Container Using Flexbox?

Posted on 2025-02-06
Browse:561

How Can I Align Elements to the Bottom of a Container Using Flexbox?

Aligning Elements to the Bottom Using Flexbox

In the provided scenario, you have a div container with various child elements. You aim to achieve a layout where the elements stack vertically, with the button always positioned at the bottom, regardless of the height of the text.

Flexbox provides a solution to this problem through auto margins. Auto margins enable the distribution of remaining space to elements with auto margins prior to alignment. One way to achieve the desired layout is to use the following CSS:

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

Alternatively, you can use a flex layout like this:

.content {
  height: 200px;
  border: 1px solid;
  display: flex;
  flex-direction: column;
}
h1, h2 {
  margin: 0;
}
a {
  margin-top: auto;
}

heading 1

heading 2

Some text more or less

Click me

This approach ensures that the text elements expand to fill the available height, while the button is pushed to the bottom of the container.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3