2016-07-29 36 views
2

我使用CSS創建了一個正確的梯形,並在其中添加了一些文本。我的問題是,我不能垂直對齊div內的文本。我的步驟顯示在問題的底部。首先,我的代碼如下所示:對齊梯形內的文本

HTML:

<div class="headersection"> 
    <div class="logosection">TEXTtext</div> 
</div> 

CSS:

body { 
    margin:0; 
} 

.headersection { 
    background-color:#222939; 
    width:100%; 
    height:75px; 
    line-height:0; 
    z-index:1; 
    color:white; 
} 

.logosection { 
    width:120px; 
    border-bottom: 75px solid #ff0000; 
    border-right: 75px solid transparent; 
} 

其次,使用上面我得到這個結果,你可以看到文本的代碼是不對齊:

enter image description here

我嘗試添加了display: table;在CSS爲.headersection,然後我說這個:

 display: table-cell; 
vertical-align: middle; 
.logosection

而且,我嘗試添加此:

display: flex; 
justify-content: center; 
align-items: center; 
.logosection

,它

水平對齊但不垂直:

enter image description here

+0

您在容器中應用彈性框樣式,在您的情況下是'.headersection'。你有一個jsfiddle或其他有用的東西嗎? – tcasey

回答

6

你可以只使用line-height,並將其設置爲div的高度:

.logosection { 
    line-height: 75px; 
    width:120px; 
    border-bottom: 75px solid #ff0000; 
    border-right: 75px solid transparent; 
} 

這裏是一個小提琴:https://jsfiddle.net/0q831mq1/

有使用變換另一種技術:

div.parent { 
 
    border: 2px solid black; 
 
    height: 150px; 
 
} 
 

 
div.vertical { 
 
    position: relative; 
 
    top: 50%; 
 
    transform: translateY(-50%); 
 
}
<div class="parent"> 
 
<div class="vertical">Vertical aligned text!</div> 
 
</div>

基於SO文檔例如「垂直對準3行代碼什麼」這樣的代碼示例通過SomeoneCC BY-SA 3.0下許可(存檔here。)©2016。

+1

我試過行高,但是你也在.headersection裏添加了display:flex,它起作用了!乾杯 –