如何在div中的同一基线上对齐h2和p

时间:2015-01-19 20:59:01

标签: html css vertical-alignment

我有一个帖子标题div,其高度为70px / 4.375em 其中包含h2类别和p时间戳

我想让它按照this picture中的说明进行对齐 (用Photoshop制作)

这是我的HTML:

<div class="post-header" style="background-color:#9377d8">
    <h2 class="category">Technology</h2>
    <p class="timestamp">Saturday, today</p>
</div>

我的CSS:

.post-header{
    height:4.375em;
    width:25em;
    margin-bottom:0;
    float:left;
}
.category{
    color:white;
    display:inline;
    float:left;
    margin:0.625em;
}

.timestamp{
    color:white;
    display:inline;
    float:right;
    margin:0.625em;
}

请帮我用CSS来获得我想要的设计

2 个答案:

答案 0 :(得分:2)

您可以按如下方式更改CSS:

.post-header {
    height:4.375em;
    width:25em;
    margin-bottom:0;
    display:block;
}
.category {
    color:white;
    display:inline-block;
    width:45%;
    margin:0.625em;
}
.timestamp {
    color:white;
    display:inline-block;
    text-align:right;
    margin:0.625em;
    width:40%;
}

这样,您可以更好地控制布局,因为您可以指定元素的宽度和垂直对齐方式。正如我们所说的那样,我会使用百分比作为保证金,但当然它会在你身上

Visit fiddle看到它的实际效果

答案 1 :(得分:1)

您可以尝试以下方法。而不是浮点数,使用带有text-align: justify的内联块。

仅当至少有两行文本时才有效,因此使用伪元素.post-header:after生成一个额外的空白行。

&#13;
&#13;
.post-header {
  height: 4.375em;
  width: 25em;
  margin-bottom: 0;
  float: left;
  text-align: justify;
}
.category {
  color: white;
  margin: 0.625em;
  display: inline-block;
}
.timestamp {
  color: white;
  margin: 0.625em;
  display: inline-block;
  text-align: right; 
}
.post-header:after {
  content: "";
  display: inline-block;
  width: 100%;
}
&#13;
<div class="post-header" style="background-color:#9377d8">
  <h2 class="category">Technology</h2>
  <p class="timestamp">Saturday, today</p>
</div>
&#13;
&#13;
&#13;

相关问题