如何将两个divs中的一个放在父元素的底部?

时间:2022-02-27 08:40:30

In this example I was able put two divs on each other at the bottom of their parent, but only because I knew the height of last div. The first one was moved a bit to the top. What if the height of #second is dynamic? How can we make them sit on each other at the bottom of parent with dynamic heights? Is it even possible with css? Please do not post JavaScript or jQuery versions.

在这个例子中,我可以将两个div放在它们父div的底部,但这仅仅是因为我知道了最后一个div的高度。如果#second的高度是动态的呢?我们怎么能让它们在有动态高度的亲本的底部相互坐着呢?有css吗?请不要发布JavaScript或jQuery版本。

2 个解决方案

#1


4  

You can use Flexbox. With justify-content: flex-end and you can move content to end of parent element, so if you want to position some other child element on top of parent you can use margin-bottom: auto. This applies if you set flex-direction: column on parent.

您可以使用Flexbox。使用rationfy -content: flex-end,您可以将内容移动到父元素的末尾,因此如果您想在父元素的顶部放置其他子元素,您可以使用margin-bottom: auto。如果您在父节点上设置了flex-direction:列,那么这将适用。

.content {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.main {
  margin-bottom: auto;
  border: 1px solid black;
}
.box {
  background: lightblue;
  margin: 5px;
}
<div class="content">
  <div class="main">Lorem ipsum dolor.</div>
  <div class="box">One</div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati vel molestiae dolores, ad, nulla harum tenetur minima aperiam debitis id atque fugit, modi error et magni eius repellendus saepe. Vero?</div>
</div>

#2


0  

You can wrap both of them in a div and set position absolute style for that div rather than applying them individually..

您可以将它们都封装在一个div中,并为这个div设置位置绝对样式,而不是单独应用它们。

working [Fiddle][1]

工作(小提琴)[1]

[1]: https://jsfiddle.net/gd5pqky7/

#1


4  

You can use Flexbox. With justify-content: flex-end and you can move content to end of parent element, so if you want to position some other child element on top of parent you can use margin-bottom: auto. This applies if you set flex-direction: column on parent.

您可以使用Flexbox。使用rationfy -content: flex-end,您可以将内容移动到父元素的末尾,因此如果您想在父元素的顶部放置其他子元素,您可以使用margin-bottom: auto。如果您在父节点上设置了flex-direction:列,那么这将适用。

.content {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.main {
  margin-bottom: auto;
  border: 1px solid black;
}
.box {
  background: lightblue;
  margin: 5px;
}
<div class="content">
  <div class="main">Lorem ipsum dolor.</div>
  <div class="box">One</div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati vel molestiae dolores, ad, nulla harum tenetur minima aperiam debitis id atque fugit, modi error et magni eius repellendus saepe. Vero?</div>
</div>

#2


0  

You can wrap both of them in a div and set position absolute style for that div rather than applying them individually..

您可以将它们都封装在一个div中,并为这个div设置位置绝对样式,而不是单独应用它们。

working [Fiddle][1]

工作(小提琴)[1]

[1]: https://jsfiddle.net/gd5pqky7/