2012-09-12 63 views
0

我有HTML的這個片段:蓋上2格跨越

<div style="display: inline-block; width: 20px; height: 20px; background-color: silver"> 
    <span style="display: inline-block; background-color: red; width: 10px; height: 20px;"></span> 
    <span style="display: inline-block; background-color: green; width: 10px; height: 20px; "></span> 
</div> 

我的目標是覆蓋外<div>的兩個跨並排側,而是一個跨度在另一個之上跨度。

如何做到這一點,所以紅色的SPAN在左邊,右邊的SPAN在右邊? (注意,我希望解決方案支持2個以上的SPAN)。

回答

2

如果你漂浮跨度,他們將並排。示例here

<div style=" width: 20px; height: 20px; background-color: silver"> 
     <span style="display: inline-block; float:left;background-color: red; width: 10px; height: 20px;"></span> 
     <span style="display: inline-block; float:left;background-color: green; width: 10px; height: 20px; "></span> 
    </div> 
2

由於跨度爲inline-block,它們之間的空白將顯示爲空格,並且下面的空格將被推下,因爲div的寬度不會佔用額外的空間。嘗試使用註釋刪除跨度之間的空白(或將它們放在同一行上)。

<div style="display: inline-block; width: 20px; height: 20px; background-color: silver"> 
    <span style="..."></span><!-- 
    --><span style="..."></span> 
</div> 

我還建議使用樣式表來設計樣式元素,而不是使用內聯CSS。這將使您的代碼更具可讀性。

0

威廉在你的問題的評估是正確的。我發現將font-size: 0添加到父元素,在你的情況下,封閉的div,就是這樣做的。

0

就像scrappedcola說,它可以通過浮動內部元件是固定的,但是當你漂浮的東西,應該是明確的,因此它可以是這樣的: -

<div style=" width: 20px; height: 20px; background-color: silver"> 
     <span style="display: inline-block; float:left;background-color: red; width: 10px; height: 20px;"></span> 
     <span style="display: inline-block; float:left;background-color: green; width: 10px; height: 20px; "></span> 
     <div style="clear: both;"></div> 
    </div> 

這裏額外的div是一個僞元素清除浮動元件

上父DIV另一種方法是使用clearfix類

CSS的clearfi類是

.clearfix:after {clear:both;content:".";display:block;height:0;visibility:hidden;} 

和您的代碼應該看起來像這樣: -

<div class="clearfix" style=" width: 20px; height: 20px; background-color: silver"> 
      <span style="display: inline-block; float:left;background-color: red; width: 10px; height: 20px;"></span> 
      <span style="display: inline-block; float:left;background-color: green; width: 10px; height: 20px; "></span> 
     </div>