2017-07-01 65 views
0

因此垂直居中的文本看起來很簡單,用justify-contentalign-items中心,但當我仔細觀察時,我可以看到文本不是真正居中的。它在角色頂部的間距較小。我試圖通過在線搜索進一步調查,我發現這個https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align,但必須有一個更簡單的解決方案。如何使用flexbox實現垂直居中文本?

https://jsfiddle.net/z7cy487o/

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
.box { 
 
    height: 10%; 
 
    width: 400px; 
 
    background: #000; 
 
    font-size: 11vh; 
 
    color: #FFF; 
 
    text-align: center; 
 
    padding: 0 20px; 
 
    margin: 20px; 
 
    display: flex; 
 
    justify-content: center; /* align horizontal */ 
 
    align-items: center;  /* align vertical */ 
 
}
<div class="box"> 
 
    C 
 
</div>

+1

這是沒有意義的,我認爲你會使用Flexbox的居中文本。是否有一些非常不尋常的特例可以解釋爲什麼你會這樣做?或者,您在不使用flexbox的情況下顯示CSS的問題,坦率地說,您展示的內容非常複雜。不應該這樣做。 – Rob

+2

不,由於您找到該文章的確切原因,沒有其他方法可以將文字垂直居中。 – LGSon

回答

-1

該解決方案基於斷Center text character ☢ vertically and horizontally within a circle (CSS) 這似乎與高度動態的工作,但在約翰內斯他的答案的評論提到了修改後的版本。我相信這個解決方案只適用於我的情況。

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
.box { 
 
    height: 10%; 
 
    width: 400px; 
 
    background: #000; 
 
    font-size: 11vh; 
 
    color: #FFF; 
 
    text-align: center; 
 
    padding: 0 20px; 
 
    margin: 20px; 
 
    display: flex; 
 
    justify-content: center; /* align horizontal */ 
 
    align-items: center;  /* align vertical */ 
 
} 
 

 
.char { 
 
    line-height: 1px; 
 
    font-family: sans-serif; 
 
    font-weight: 500; 
 
    position: relative; 
 
    top: 0.05em; 
 
}
<div class="box"> 
 
    <span class="char">C</span> 
 
</div>

4

您認爲這取決於哪個字符您正在使用的方式。我複製了你的例子兩次,以顯示不同的情況:

在第二個版本中,我只使用了字母「y」,它有一個下降部分,即延伸到基線以下的部分,定義爲line-height。另一方面,它並不是完整的,所以它看起來與第一個版本(字母「C」)在垂直對齊方面完全相反。

在第三個版本中,我將這兩個字母組合在一起。在這裏你可以看到不同的字符/字母在一起確實是做的在整個寬度上延伸,所以垂直居中是正確的。

LINE-HEIGHT(以及有關的是,字母垂直排列)不取決於其使用字母 - 它總是適用於所有可能的字母/字符,即使他們沒有在特定的情況下使用。

html, body { height: 100%; } 
 
.box 
 
{ 
 
    height: 10%; 
 
    width: 400px; 
 
    background: #000; 
 
    font-size: 11vh; 
 
    color: #FFF; 
 
    text-align: center; 
 
    padding: 0 20px; 
 
    margin: 20px; 
 
    display: flex; 
 
    justify-content: center; /* align horizontal */ 
 
    align-items: center; /* align vertical */ 
 
}
<div class="box"> 
 
C 
 
</div> 
 

 
<div class="box"> 
 
y 
 
</div> 
 

 
<div class="box"> 
 
Cyborg 
 
</div>

+0

這解釋了爲什麼它不工作,但你知道如何垂直居中在一個字符在div? –

+0

這取決於它是哪個字符。基本上你只能嘗試不同的'padding-top'和'padding-bottom'設置。但即使如此,您仍然有可能在不同的字體中使用不同的比例。它也取決於字體大小和行高。這是一個反覆試驗的過程,它總是隻適用於某種特定的情況。 – Johannes