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

How to align h2 and p on same basline in div

我有一个高度为 70px/4.375em 的 post header div 其中有一个类别 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 得到我想要的设计

您可以按如下方式更改您的 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 实际操作

您可以尝试以下方法。使用带 text-align: justify.

的内联块而不是浮点数

这仅在至少有两行文本的情况下有效,因此使用伪元素 .post-header:after.

生成一个额外的空行

.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%;
}
<div class="post-header" style="background-color:#9377d8">
  <h2 class="category">Technology</h2>
  <p class="timestamp">Saturday, today</p>
</div>