假设我有以下CSS和HTML代码:
null
#header {
height: 150px;
}
<div id="header">
<h1>Header title</h1>
Header content (one or multiple lines)
</div>
null
页眉部分的高度是固定的,但页眉内容可能会改变。
我希望页眉的内容垂直对齐到页眉部分的底部,这样最后一行文本就“粘”到了页眉部分的底部。
所以如果只有一行文字,就会像:
----------------------------- | 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中做到这一点?
相对+绝对定位是你的最佳选择:
null
#header {
position: relative;
min-height: 150px;
}
#header-content {
position: absolute;
bottom: 0;
left: 0;
}
#header, #header * {
background: rgba(40, 40, 100, 0.25);
}
<div id="header">
<h1>Title</h1>
<div id="header-content">Some content</div>
</div>
使用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所指出的那样,您需要标识header-content来使其工作。
<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>
如果你不担心传统浏览器,就使用Flexbox。
父元素需要将其显示类型设置为flex
div.parent {
display: flex;
height: 100%;
}
然后将子元素的align-self设置为flex-end。
span.child {
display: inline-block;
align-self: flex-end;
}
以下是我学习的资源:http://css-tricks.com/snippets/css/a-guide-to-flexbox/