簡體   English   中英

如何水平和垂直對齊內聯塊

[英]How to align an inline-block horizontally and vertically

什么是最好/最干凈的使用CSS#dates div與標題的右側對齊,並在中間垂直對齊。

我試過float: right ,但這不允許vertical-align 我想避免使用浮點數,所以我使用inline-block ,並使用相對定位。 有更正確的方法嗎?

我不喜歡這樣一個事實,即我必須做一個30px的頂部,並使用反復試驗直到它居中。

<div id="header">
    <a id="logo" href="~/" runat="server">
        <img src="Images/Interface/logo.png" alt="logo" />
    </a>
    <div id="dates">
        <div id="hijri-date">2 Ramadhaan, 1435 AH</div>
        <div id="gregorian-date">Sunday 29 June 2014</div>
    </div>
</div>

#header
{
    background-color: white;
    padding: 15px;
    position: relative;
}

#logo
{
    display: inline-block;
    vertical-align: middle;
}

    #logo img
    {
        vertical-align: bottom; /* to get rid of text descender space underneath image */
    }

#dates
{
    display: inline-block;
    position: absolute;
    right: 30px;
    top: 30px;
    font-size: 14px;
    font-family: 'Open Sans';
    color: #696969;
    background: url(Images/Interface/date-icon.png) no-repeat;
    background-position-y: center;
    padding-left: 32px;
}

你可以使用css display:table

#header {display:table; width:100%;}
#logo,
#dates {display:table-cell; vertical-align:middle}

如果希望#dates與右側對齊,則可能需要為#dates提供寬度

使用內聯塊

使用發布的HTML元素,嘗試以下CSS:

#header {
    background-color: yellow;
    padding: 15px;
    text-align: justify;
    line-height: 0;
}
#logo {
    display: inline-block;
    vertical-align: middle;
}
#logo img {
    vertical-align: bottom; 
        /* to get rid of text descender space underneath image */
}
#dates {
    display: inline-block;
    line-height: 1.5;
    font-size: 14px;
    font-family:'Open Sans';
    color: black;
    background-image: url(http://placehold.it/100x100);
    background-position: center;
    padding-left: 32px;
}
#header:after {
    content: '';
    display: inline-block;
    vertical-align: top;
    width: 100%;
}

由於#header有兩個子元素,左側徽標圖像和右側文本塊,只需使用text-align: justify強制徽標在左側,文本在右側。

要使其工作,您需要在#header中至少有兩行。

要生成第二行,請使用偽元素: #header:after將在日期之后放置一個100%寬的空內聯塊。 width: 100%強制它開始並填充第二行, vertical-align: top去除基線下方的額外空白區域。

要處理高度中的空白區域,請在#header設置line-height: 0 ,這將允許偽元素的高度折疊為0.但是,您需要重置line-height: 1.5 in #dates to得到清晰的文字。

優點和缺點

使用這種方法,當頁面寬度變小時,元素最終會換行到兩行。

如果要將元素保留在一行中,最好使用CSS表。

見演示: http//jsfiddle.net/audetwebdesign/3U3w4/

使用display: flex; 您可以將項目設置為水平和垂直居中。

我認為,垂直對齊的最佳方法是使用css:display-tablecss"display-table-cell properties。如果你想在id =”dates“中對齊正確的內容,你應該使用css:display-inline-table inside這個街區。

#header {
    background: #fff;
    padding: 15px;
    background: #ccc;
    display: table;
}
#logo {
    display: table-cell;
}
#dates {
    display: table-cell;
    text-align: right;
    font-size: 14px;
    font-family: 'Open Sans';
    color: #696969;
}

見小提琴

暫無
暫無

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

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