假设我有以下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中做到这一点?


当前回答

这里是另一个解决方案使用flexbox,但没有使用flex-end底部对齐。这个想法是在h1上设置margin-bottom,以自动将剩余的内容推到底部:

#标题{ 身高:350 px; 显示:flex; flex-direction:列; 边界:1 px固体; } #标题h1 { margin-bottom:汽车; } < div id = "头" > <标题>标题< / h1 > 页眉内容(一行或多行)页眉内容(一行或多行)页眉内容(一行或多行)页眉内容(一行或多行) < / div >

我们也可以对文本的margin-top:auto做同样的事情,但在这种情况下,我们需要将它包装在div或span中:

#标题{ 身高:350 px; 显示:flex; flex-direction:列; 边界:1 px固体; } #头span { margin-top:汽车; } < div id = "头" > <标题>标题< / h1 > <span>标头内容(一行或多行)</span> < / div >

其他回答

如果你有多个动态高度项,使用CSS显示table和table-cell的值:

HTML

<html>
<body>

  <div class="valign bottom">
    <div>

      <div>my bottom aligned div 1</div>
      <div>my bottom aligned div 2</div>
      <div>my bottom aligned div 3</div>

    </div>
  </div>

</body>
</html>

CSS

html,
body {
  width: 100%;
  height: 100%;
}
.valign {
  display: table;
  width: 100%;
  height: 100%;
}
.valign > div {
  display: table-cell;
  width: 100%;
  height: 100%;
}
.valign.bottom > div {
  vertical-align: bottom;
}

我在这里创建了一个JSBin演示:http://jsbin.com/INOnAkuF/2/edit

演示也有一个例子如何垂直中心对齐使用相同的技术。

一个非常简单的单行解决方案是为div添加行高,记住所有div的文本都将放在底部。

CSS:

#layer{width:198px;
       height:48px;
       line-height:72px;
       border:1px #000 solid}
#layer a{text-decoration:none;}

HTML:

<div id="layer">
    <a href="#">text at div's bottom.</a>
</div>

请记住,这是一个实用和快速的解决方案,当你只是想在div里的文本下去,如果你需要结合图像和东西,你将不得不编码一个更复杂的和响应性的CSS

我想出了一个比上面提到的简单得多的方法。

设置标题div的高度。然后在里面,样式H1标签如下:

float: left;
padding: 90px 10px 11px

我在一个客户的网站上工作,设计要求文本在某个div的底部。我已经使用这两行实现了结果,它工作得很好。此外,如果文本确实展开,填充将保持不变。

如果你可以设置内容的包装div的高度(#header-content,如other's reply所示),而不是整个#header,也许你也可以尝试这种方法:

HTML

<div id="header">
    <h1>some title</h1>
    <div id="header-content">
        <span>
            first line of header text<br>
            second line of header text<br>
            third, last line of header text
        </span>
    </div>
</div>

CSS

#header-content{
    height:100px;
}

#header-content::before{
  display:inline-block;
  content:'';
  height:100%;
  vertical-align:bottom;
}

#header-content span{
    display:inline-block;
}

在代码依赖上显示

试一试:

div.myclass { margin-top: 100%; }

尝试更改%来修复它。例如:120%或90%等等。