假设我有以下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。请参阅下面的示例。你甚至不需要一些文本…因为直接包含在伸缩容器中的文本被包装在匿名伸缩项中。

标题{ 边框:1px纯蓝色; 身高:150 px; 显示:flex;/*定义flexbox */ flex-direction:列;/*从上到下*/ justify-content:之间的空间;/*开始的第一项,结束的最后一项*/ } h1 { 保证金:0; } <标题> <标题>标题< / h1 > 一些文本对齐到底部 头> < /

如果只有一些文本,你想垂直对齐到容器的底部。

节{ 边框:1px纯蓝色; 身高:150 px; 显示:flex;/*定义flexbox */ 对齐项目:flex-end;/*盒子底部*/ } 一些文本对齐到底部</section>

其他回答

这是一种灵活的方法。当然,IE8不支持,7年前用户就需要了。根据您需要支持的内容,其中一些可以取消。

不过,如果有一种方法来做到这一点,没有一个外部容器,这将是很好的,只是让文本在它自己的自我对齐。

#header {
    -webkit-box-align: end;
    -webkit-align-items: flex-end;
    -ms-flex-align: end;
    align-items: flex-end;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    height: 150px;
}

您可以使用以下方法:

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

#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 >

如果你可以设置内容的包装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移到底部的最佳解决方案如下所示。 基本上,你需要做的是将display flex和flex-direction设置为父类的列,并将'margin-top: auto'添加到它的子类,该子类需要被浮动到容器的底部 注意:我已经使用了bootstrap及其类。

.box-wrapper { 身高:400 px; 边框:1px实心#000; 保证金:20 px; 显示:flex;//仅用于表示。引导默认类已经添加 flex-direction:列; } .link-02 { margin-top:汽车; } <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet" /> <div class="box-wrapper d-flex flex-column col-4"> <div>意外blanditiis debitis</div> < div class = " news-box”> <img class="d-block" alt="non ipsam nihil" src="https://via.placeholder.com/150"> <p>连续痛苦的分娩和面对的分娩</p> < / div > <a href="https://oscar.com" target="_blank" class="link-02"> 这是移动到底部与最小的努力 < / > < / div >