假设我有以下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 >
在为同样的问题挣扎了一段时间后,我终于找到了一个满足我所有要求的解决方案:
不需要我知道容器的高度。
与相对+绝对解决方案不同,内容不会漂浮在自己的层中(即,它通常嵌入在容器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>