簡體   English   中英

如何在div中的同一基線上對齊h2和p

[英]How to align h2 and p on same basline in div

我有一個高度為70px / 4.375em的帖子標頭div ,它是類別h2p時間戳

我希望按照圖片所示對齊(在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%;
}

這樣,由於可以同時指定元素的寬度和垂直對齊方式,因此可以更好地控制布局。 就目前而言,我會使用百分比作為保證金,但是當然會

參觀小提琴以查看實際效果

您可以嘗試以下方法。 而不是浮點數,請使用帶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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM