CSS定位在底部,没有绝对定位 [英] CSS positioning at the bottom without absolute positioning

查看:429
本文介绍了CSS定位在底部,没有绝对定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定位元素,使其始终位于容器的底部而不使用绝对"定位? 我有一个包含2个元素的容器,其中之一是文本描述,因此它可以与文本一样大.我想将第二个元素放置在页面底部,无论上一个div中的文本是否为空,如果文本不为空,我都希望它们之间有10px的填充

How can I position an element so it is always on the bottom of the container without using 'absolute' positioning? I have a container containing 2 elements and one of them is text description so it can be as big as the text is. I would like to position second element at the bottom of the page regardless if the text in previous div is empty, and If text isn't empty I want to have padding of 10px between them

推荐答案

已更新:将flexbox应用于代码的JSFiddle.

Updated: JSFiddle with flexbox applied to your code.

https://jsfiddle.net/ec7qxtfr/1/

flexbox可以帮助您实现这一目标.将以下内容添加到您的父容器中.

flexbox can help you achieve this. Add the following to your parent container.

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

下一位是您想要的10px填充的.这将定位到容器内的第一个子元素.

The next bit is for the 10px padding you wanted. This will target the first child element inside the container.

.child:first-child {
  padding-bottom: 10px;
}

只要存在第一个子元素div,即使您没有任何内容(无段落),由于flexbox,第二个div仍将推入容器的底部.同样,您可以注释掉height属性,以验证两个子元素之间是否存在padding.

As long as the first child div is present, even if you don't have any content (no paragraphs), the second div will still be pushed to the bottom of the container thanks to flexbox. Likewise, you can comment out the height property to verify that the padding is present between the two child elements.

查看下面的JSFiddle.您可以调整父容器中的高度,以确认第二个div停留在容器的底部.

Check out the JSFiddle below. You can adjust the height in the parent container to confirm that the second div stays at the bottom of the container.

https://jsfiddle.net/o3r40keu/5/

注意:此解决方案将假定您在此特定父容器内只有两个子元素.

Note: this solution will assume you will only have two child elements inside this particular parent container.

我希望这会有所帮助!

这篇关于CSS定位在底部,没有绝对定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆