2017-04-21 60 views
4

爲什麼阻止文本轉移到底部?我知道如何解決這個問題(需要在框中添加「overflow:hidden」),但我不明白爲什麼它會移到底部,框內的文本很短,瀏覽器檢查器中的邊距與邊距相同沒有文字的例子。爲什麼文本塊向下移動?

Example of the problem

HTML:

<div class="with-text"> 
    <div class="box1"> 
    SIMPLE TEXT 
    </div> 
    <div class="box2"> 
    </div> 
</div> 
<div class="without-text"> 
    <div class="box1"> 
    </div> 
    <div class="box2"> 
    </div> 
</div> 

CSS:

html, body { 
    font-size: 10px; 
    margin: 0; 
    height: 100%; 
} 

.box1 { 
    display: inline-block; 
    margin: 5px; 
    width: 50px; 
    height: 50px; 
    background: blue; 
    /* Fix the problem */ 
    /* overflow: hidden; */ 
    color: white; 
} 

.box2 { 
    display: inline-block; 
    margin: 5px; 
    width: 50px; 
    height: 50px; 
    background: red; 
} 

.with-text:before { 
    display: block; 
    content: "with-text"; 
    text-transform: uppercase; 
    margin: 1rem; 
} 

.with-text { 
    box-sizing: border-box; 
    height: 50%; 
    border: 1px solid; 
} 

.without-text:before { 
    display: block; 
    content: "without text"; 
    text-transform: uppercase; 
    margin: 1rem; 
} 

.without-text { 
    box-sizing: border-box; 
    height: 50%; 
    border: 2px solid black; 
} 
+1

添加'vertical-align:top',否則會嘗試對齊元素中的文本。 –

+0

而不是顯示:inline-block你也可以用flexbox的方法 – k185

回答

1

的問題是,在默認情況下基線

內部元件的文本會影響它與推動div來的底部 - 內嵌元素的垂直取向。

使用vertical-align: top來解決問題。

+0

謝謝,現在我明白了!帶有內聯塊屬性的div存在於文本流中,因爲它通過文本屬性進行對齊 – Azat

0

你可以嘗試添加垂直對齊:

.box1 { 
    display: inline-block; 
    margin: 5px; 
    width: 50px; 
    height: 50px; 
    background: blue; 
    /* overflow: hidden; */ 
    color: white; 
    vertical-align:top; 
} 
相關問題