如何将div的内容对齐到底部

新手上路,请多包涵

假设我有以下 CSS 和 HTML 代码:

 #header {
  height: 150px;
}
 <div id="header">
  <h1>Header title</h1>
  Header content (one or multiple lines)
</div>

标题部分是固定高度,但标题内容可能会改变。

我希望标题的内容与标题部分的底部垂直对齐,因此最后一行文本“粘”在标题部分的底部。

所以如果只有一行文本,它会是这样的:

------------------------------
|标题标题
|
|
|
|标题内容(产生一行)
------------------------------

如果有三行:

------------------------------
|标题标题
|
|标头内容(这是
|很多东西,它很完美
|跨越三行)
------------------------------

这在 CSS 中如何实现?

原文由 kristof 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 702
2 个回答

相对+绝对定位是你最好的选择:

 #header {
  position: relative;
  min-height: 150px;
}

#header-content {
  position: absolute;
  bottom: 0;
  left: 0;
}

#header, #header * {
  background: rgba(40, 40, 100, 0.25);
}
 <div id="header">
  <h1>Title</h1>
  <div id="header-content">And in the last place, where this might not be the case, they would be of long standing, would have taken deep root, and would not easily be extirpated. The scheme of revising the constitution, in order to correct recent breaches of it, as well as for other purposes, has been actually tried in one of the States.</div>
</div>

但是您可能会遇到问题。当我尝试它时,我遇到了下拉菜单出现在内容下方的问题。它只是不漂亮。

老实说,对于垂直居中问题以及项目的任何垂直对齐问题都不是固定高度,使用表格会更容易。

示例: 您可以在不使用表格的情况下完成此 HTML 布局吗?

原文由 cletus 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您不担心旧版浏览器,请使用 flexbox。

父元素需要将其显示类型设置为 flex

 div.parent {
  display: flex;
  height: 100%;
}

然后将子元素的 align-self 设置为 flex-end。

 span.child {
  display: inline-block;
  align-self: flex-end;
}

这是我用来学习的资源:http: //css-tricks.com/snippets/css/a-guide-to-flexbox/

原文由 Lee Irvine 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题