2014-10-29 72 views
1

我有一個代碼問題:垂直對齊誤解

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
     .circle { 
      width: 16px; 
      height: 16px; 
      border-radius: 50%; 
      border: 1px solid black; 
     } 

     .circle.red { 
      background-color: red; 
     } 

     .circle.green { 
      background-color: green; 
     } 

     .circle.blue { 
      background-color: blue; 
     } 

     .some_class { 
      height: 24px; 
      width: 320px; 
      border: 1px solid black; 
      background: yellow; 
     } 

     .some_class div { 
      display: inline-block; 
      background-color: aqua; 
     } 

     .some_class .circle { 
      margin: 3px 3px 3px 3px;; 
     } 

     .some_class .title { 
      background-color: blueviolet; 
     } 
    </style> 
</head> 
<body> 
    <div id="some_id" class="some_class"> 
     <div class="circle green"> 

     </div> 
     <div class="title"> 
      Some title 
     </div> 
     <div class="text"> 
      Some text 
     </div> 
    </div> 
</body> 
</html> 

這裏的問題是,「一些標題」和「某些文本」塊顯示在下面的綠色圓圈的中心。而且這些街區甚至不在<div id="some_id">之內。 我該如何解決它?如果我可以將這些div垂直對齊到主div的中間,那將會很棒。但至少我想讓他們找到那個div的內部。 我可以做這樣的事情:

.some_class .title { 
      background-color: blueviolet; 
      position: relative; 
      top: -7px; 
     } 

,但它不到風度似乎是正確的,因爲我仍然無法理解爲什麼他們不在主要股利。

+0

你能建立一個的jsfiddle給我們,好了,擺弄? – Rvervuurt 2014-10-29 12:19:53

回答

0

由於您的3個孩子div設置爲display: inline-block,因此它們的默認vertical-align屬性設置爲baseline,這就是爲什麼它們不是垂直對齊的原因。您將需要添加vertical-align: middle到所有3兒童的div像這樣:

.text, .title, .circle { 
    vertical-align: middle; 
} 

jsFiddle Demo

.circle { 
 
    width: 16px; 
 
    height: 16px; 
 
    border-radius: 50%; 
 
    border: 1px solid black; 
 
} 
 
.circle.red { 
 
    background-color: red; 
 
} 
 
.circle.green { 
 
    background-color: green; 
 
} 
 
.circle.blue { 
 
    background-color: blue; 
 
} 
 
.some_class { 
 
    height: 24px; 
 
    width: 320px; 
 
    border: 1px solid black; 
 
    background: yellow; 
 
} 
 
.some_class div { 
 
    display: inline-block; 
 
    background-color: aqua; 
 
} 
 
.some_class .circle { 
 
    margin: 3px 3px 3px 3px; 
 
    ; 
 
} 
 
.some_class .title { 
 
    background-color: blueviolet; 
 
} 
 
.text, 
 
.title, 
 
.circle { 
 
    vertical-align: middle; 
 
}
<div id="some_id" class="some_class"> 
 
    <div class="circle green"></div> 
 
    <div class="title">Some title</div> 
 
    <div class="text">Some text</div> 
 
</div>

1

對於默認vertical-alignbaseline作爲參考的文本的基礎。只要改變該屬性:

.some_class div { 
    display: inline-block; 
    vertical-align:middle; /*ADD THIS LINE*/ 
    background-color: aqua; 
} 

入住這DemoFiddle