我从基础开始学习html和css。我正在编写一些简单的网站。我有一个关于对齐h2垂直底部的问题。
我想要实现的是头部的背景图像(高度240px),有一个黑色的文字条:"爱黄瓜"对齐到它的底部。我尝试了多种方法,但都不起作用。
文本应该是"你应该爱黄瓜的9个理由"。
下面是相关的css和html:
.body {
clear: both;
width: 800px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
}
header {
height: 240px;
margin: 1em auto 3em;
background-image: url("https://media.mercola.com/ImageServer/Public/2014/August/cucumber-health-benefits-fb.jpg");
background-size: cover;
text-align: center;
font-family: 'Lobster', Georgia, Times, serif;
}
#caption {
width: 100%;
height: 70px;
line-height: 70px;
background: #191919;
color: #ffffff;
font-size: 2em;
letter-spacing: 1px;
border-bottom-left-radius: 15px;
-webkit-border-bottom-left-radius: 15px;
-moz-border-radius-bottomleft: 15px;
border-bottom-right-radius: 15px;
-webkit-border-bottom-right-radius: 15px;
-moz-border-radius-bottomright: 15px;
<header class="body">
<h2 id="caption">Love cucumbers <3</h2>
</header>
可以使用相对位置来设置header,使用绝对位置来设置h2。请看下面更新后的代码
.body {
clear: both;
width: 800px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
}
header {
height: 240px;
margin: 1em auto 3em;
background-image: url("https://media.mercola.com/ImageServer/Public/2014/August/cucumber-health-benefits-fb.jpg");
background-size: cover;
text-align: center;
font-family: 'Lobster', Georgia, Times, serif;
position:relative;
}
#caption {
width: 100%;
height: 70px;
line-height: 70px;
background: #191919;
color: #ffffff;
font-size: 2em;
letter-spacing: 1px;
position:absolute;
bottom:0px;
margin-bottom:0px;
border-bottom-left-radius: 15px;
-webkit-border-bottom-left-radius: 15px;
-moz-border-radius-bottomleft: 15px;
border-bottom-right-radius: 15px;
-webkit-border-bottom-right-radius: 15px;
-moz-border-radius-bottomright: 15px; }
<header class="body">
<h2 id="caption">Love cucumbers <3</h2>
</header>
您必须将标题的行高设置为与标题相同的高度。
#caption {
width: 100%;
height: 100%;
line-height: 240px;
}
这是一个工作小提琴
我将这些属性添加到.body class
display: table;
position: relative;
height: 200px; /* Edit this with as you wish */
和#caption id
display: table-cell;
vertical-align: bottom;
PS: table-cell
元素的background-image属性不起作用,所以我对body tag
元素应用了background-image。