假设我有以下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>

其他回答

使用CSS定位:

/* Creates a new stacking context on the header */
#header {
  position: relative;
}

/* Positions header-content at the bottom of header's context */
#header-content {
  position: absolute;
  bottom: 0;
}

正如cletus所指出的,您需要确定头内容来完成这项工作。

<span id="header-content">some header content</span>

<div style="height:100%; position:relative;">
    <div style="height:10%; position:absolute; bottom:0px;">bottom</div>
</div>

我发现这个解决方案基于一个默认的引导启动模板

/* HTML */

<div class="content_wrapper">
  <div class="content_floating">
    <h2>HIS This is the header<br>
      In Two Rows</h2>
    <p>This is a description at the bottom too</p> 
  </div>
</div>

/* css */

.content_wrapper{
      display: table;
      width: 100%;
      height: 100%; /* For at least Firefox */
      min-height: 100%;
    }

.content_floating{
  display: table-cell;
  vertical-align: bottom;
  padding-bottom:80px;

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

你不需要绝对+相对。对于容器和数据都使用相对位置是非常可能的。这就是你要做的。

假设你的数据高度是x。你的容器是相对的,页脚也是相对的。你所要做的就是添加你的数据

bottom: -webkit-calc(-100% + x);

您的数据将始终位于容器的底部。即使你有动态高度的容器也能工作。

HTML是这样的

<div class="container">
  <div class="data"></div>
</div>

CSS是这样的

.container{
  height:400px;
  width:600px;
  border:1px solid red;
  margin-top:50px;
  margin-left:50px;
  display:block;
}
.data{
  width:100%;
  height:40px;
  position:relative;
   float:left;
  border:1px solid blue;
  bottom: -webkit-calc(-100% + 40px);
   bottom:calc(-100% + 40px);
}

这里有一个活生生的例子

希望这能有所帮助。

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

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

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

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