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

#标题{ 身高:150 px; } < div id = "头" > <标题>标题< / h1 > 标题内容(一行或多行) < / div >

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

我想要标题的内容垂直对齐到标题部分的底部,所以最后一行文本“粘”到标题部分的底部。

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

-----------------------------
| Header title
|
|
|
| header content (resulting in one line)
-----------------------------

如果有三行:

-----------------------------
| Header title
|
| header content (which is so
| much stuff that it perfectly
| spans over three lines)
-----------------------------

如何在CSS中做到这一点?


当前回答

您可以使用以下方法:

.header-parent { 身高:150 px; 显示:网格; } .header-content { align-self:结束; } < div class = " header-parent”> <标题>标题< / h1 > < div class = "标题内容”> 标题内容 < / div > < / div >

其他回答

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

#标题{ 位置:相对; 最小高度:150 px; } #标题内容{ 位置:绝对的; 底部:0; 左:0; } #header, #header * { 背景:rgba(40,40,100,0.25); } < div id = "头" > h1标题< h1 > < / > 在最后一个地方,情况可能不是这样,他们会长期存在,会深深地扎根,不会轻易被铲除。修改宪法的计划,为了纠正最近的违反宪法的行为,以及其他目的,实际上已经在一个州尝试过了 < / div >

但你可能会遇到问题。当我尝试它时,我遇到了下拉菜单出现在内容下面的问题。这并不漂亮。

老实说,对于垂直定心问题,以及任何与物品的垂直对齐问题都不是固定高度的问题,使用表格更容易。

例子:你可以不使用表格来做这个HTML布局吗?

如果父元素/块元素的行高大于Inline元素的行高,Inline或Inline块元素可以对齐到块级元素的底部

标记:

<h1 class="alignBtm"><span>I'm at the bottom</span></h1>

css:

h1.alignBtm {
  line-height: 3em;
}
h1.alignBtm span {
  line-height: 1.2em;
  vertical-align: bottom;
}

*确保你在标准模式

在为同样的问题挣扎了一段时间后,我终于找到了一个满足我所有要求的解决方案:

不需要我知道容器的高度。 与相对+绝对解决方案不同,内容不会漂浮在自己的层中(即,它通常嵌入在容器div中)。 支持跨浏览器(IE8+)。 易于实现。

解决方案只需要一个<div>,我称之为“对齐器”:

CSS

.bottom_aligner {
    display: inline-block;
    height: 100%;
    vertical-align: bottom;
    width: 0px;
}

html

<div class="bottom_aligner"></div>
... Your content here ...

这个技巧通过创建一个高而细的div来实现,它将文本基线推到容器的底部。

下面是一个完整的例子,实现了OP的要求。为了演示,我将“bottom_aligner”设置为粗大的红色。

CSS:

.outer-container {
  border: 2px solid black;
  height: 175px;
  width: 300px;
}

.top-section {
  background: lightgreen;
  height: 50%;
}

.bottom-section {
  background: lightblue;
  height: 50%;
  margin: 8px;
}

.bottom-aligner {
  display: inline-block;
  height: 100%;
  vertical-align: bottom;
  width: 3px;
  background: red;
}

.bottom-content {
  display: inline-block;
}

.top-content {
  padding: 8px;
}

HTML:

<body>
  <div class="outer-container">
    <div class="top-section">
      This text
      <br> is on top.
    </div>
    <div class="bottom-section">
      <div class="bottom-aligner"></div>
      <div class="bottom-content">
        I like it here
        <br> at the bottom.
      </div>
    </div>
  </div>
</body>

我刚刚为客户端做的网站要求页脚文本是一个高框,在底部的文本我实现了这个简单的填充,应该适用于所有浏览器。

<div id="footer">
  some text here
</div>
#footer {
  padding: 0 30px;
  padding-top: 60px;
  padding-bottom: 8px;
}
#header {
    height: 150px;
    display:flex;
    flex-direction:column;
}

.top{
    flex: 1;
}   

<div id="header">
    <h1 class="top">Header title</h1>
    Header content (one or multiple lines)
</div>

#标题{ 身高:250 px; 显示:flex; flex-direction:列; 背景颜色:黄色; } .top { flex: 1; } < div id = "头" > <h1 class="top">头标题</h1> 标题内容(一行或多行) < / div >