假设我有以下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的高度(#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中)。
支持跨浏览器(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>