2013-04-10 62 views
2

我嘗試水平居中2個divs並對齊它們之間的這2個div。當我在每個div中放入不同大小的文本時,問題就來了。以下是示例:http://jsfiddle.net/DgEcs/1/中心2文本與文本

爲什麼紅色的div會向下移動以及如何解決?
CSS:

.container{ 
    margin: 20px auto; 
    height: 50px; line-height: 50px; 
    text-align: center; /* to center red and blue */ 
    background: whiteSmoke; 
} 
.red{ 
    display:inline-block; /* to put it side by side */ 
    font-size: 10px; 
    background:red; 
} 
.blue{ 
    display:inline-block; /* to put it side by side */ 
    font-size: 26px; 
    background:blue; 
} 

HTML:

<div class="container" > 
    <div class="red"> aaaaaaa </div> 
    <div class="blue"> bbbbbbb </div> 
</div> 

回答

2

添加vertical-align: top;到兩個.red.blue

+0

好,它的工作原理。你知道爲什麼會發生?我之前嘗試過:vertical-align:center;它不起作用,你明白爲什麼嗎? – Nrc 2013-04-10 14:06:32

2

的CSS只需添加vertical-align:top。另外你可以優化你的CSS ...

http://jsfiddle.net/DgEcs/4/

.container div { 
    vertical-align:top; 
    display:inline-block; 
} 

.red{ 
    font-size: 10px; 
    background:red; 
} 

.blue{ 
    font-size: 26px; 
    background:blue; 
} 

現在看起來應該是這樣: Screenshot taken from Chrome 26/OSX

+0

好的,它的工作原理。你知道爲什麼會發生?我之前嘗試過:vertical-align:center;它不起作用,你明白爲什麼嗎? – Nrc 2013-04-10 14:05:51

+0

你的小提琴是正確的。但是當你優化CSS時:1.容器不會在頁面中水平居中2紅色和藍色也不在它們之間居中。我不明白你的答案? – Nrc 2013-04-10 14:10:39

+0

我的jsfiddle正在使用優化的樣式,並應正常工作。您正在使用哪個瀏覽器? – gearsdigital 2013-04-10 14:22:20