2017-02-24 26 views
2

我有這樣的代碼:如何對齊文本<a>元素垂直,即顯示爲塊

a { 
 
    display: block; 
 
    width: 231px; 
 
    height: 52px; 
 
    background-color: #ffffff; 
 
    color: #0275d8; 
 
    border: 1px solid #0275d8; 
 
    -webkit-border-radius: 4px; 
 
    -moz-border-radius: 4px; 
 
    border-radius: 4px; 
 
    text-align: center; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
    font: 16px 'Lato', sans-serif; 
 
}
<a href="#">some text</a> 
 
</br> 
 
<a href="#">some text that is bigger than in the first link</a>

有什麼辦法,我可以垂直對齊文本?恕我直言,這裏使用填充不是一個好主意。任何幫助將不勝感激。謝謝。

回答

3

您可以使用Flexbox並將文本與align-items: center對齊。

a { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    width: 231px; 
 
    height: 52px; 
 
    background-color: #ffffff; 
 
    color: #0275d8; 
 
    border: 1px solid #0275d8; 
 
    border-radius: 4px; 
 
    text-align: center; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
    font: 16px 'Lato', sans-serif; 
 
}
<a href="#">some text</a> 
 
<br> 
 
<a href="#">some text that is bigger than in the first link</a>

+0

非常感謝,它的工作原理。我試過這個解決方案,但沒有'justify-content:center;',所以我認爲這是一個錯誤的方法。 –

1

我總是用一個Flexbox的爲這樣的事情。用css佈置內容是很了不起的。 Flexbox的a great reference

在這種情況下,您只需添加display: flex; justify-content: center; align-items: center;,並刪除margin-left: auto;margin-right: auto;

a { 
 
    display: flex; 
 
    justify-content: center; 
 
    align-items: center; 
 
    width: 231px; 
 
    height: 52px; 
 
    background-color: #ffffff; 
 
    color: #0275d8; 
 
    border: 1px solid #0275d8; 
 
    -webkit-border-radius: 4px; 
 
    -moz-border-radius: 4px; 
 
    border-radius: 4px; 
 
    text-align: center; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
    font: 16px 'Lato', sans-serif; 
 
}
<a href="#"><span>some text</span></a> 
 
</br> 
 
<a href="#"><span>some text that is bigger than in the first link</span></a>

1

我建議ü更改爲display:table和裏面添加一個表格單元格,u可以使用任何標記,就像一個span

a { 
 
    display: table; 
 
    width: 231px; 
 
    height: 52px; 
 
    background-color: #ffffff; 
 
    color: #0275d8; 
 
    border: 1px solid #0275d8; 
 
    -webkit-border-radius: 4px; 
 
    -moz-border-radius: 4px; 
 
    border-radius: 4px; 
 
    text-align: center; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
    font: 16px 'Lato', sans-serif; 
 
} 
 
a span{ 
 
    display:table-cell; 
 
    vertical-align:middle; 
 
}
<a href="#"><span>some text</span></a> 
 
</br> 
 
<a href="#"><span>some text that is bigger than in the first link</span></a>

display:flex不適用於所有naviga表&表格單元是「垂直對齊」容器內物體的最佳選擇