2012-12-06 37 views
0

我有示範下面的代碼:HTML/CSS:如何將'a href'元素浮動到左側而不留下它們所在的div元素?

<html> 
    <head> 
     <style type="text/css"> 
      a{ 
       display:block; 
       float:left; 
      } 
      #linkDiv{ 
       border-style:solid; 
      } 
     </style> 
    </head> 
    <body> 
     <div id="linkDiv"> 
      <a href="">test</a> 
      <a href="">test</a> 
      <a href="">test</a> 
     </div> 
    </body> 
</html> 

我想我的鏈接是塊,還他們每個人是旁邊其他。如果沒有float:left這就是我得到:

enter image description here

然而,當我使用float:left這就是結果:

enter image description here

在此先感謝

回答

2

你需要一個 「clearfix」 上父元素:

overflow: hidden; 

或者

/** 
* For modern browsers 
* 1. The space content is one way to avoid an Opera bug when the 
* contenteditable attribute is included anywhere else in the document. 
* Otherwise it causes space to appear at the top and bottom of elements 
* that are clearfixed. 
* 2. The use of `table` rather than `block` is only necessary if using 
* `:before` to contain the top-margins of child elements. 
*/ 
.cf:before, 
.cf:after { 
    content: " "; /* 1 */ 
    display: table; /* 2 */ 
} 

.cf:after { 
    clear: both; 
} 

/** 
* For IE 6/7 only 
* Include this rule to trigger hasLayout and contain floats. 
*/ 
.cf { 
    *zoom: 1; 
} 

http://nicolasgallagher.com/micro-clearfix-hack/

0

嘗試

overflow: auto 

在含div

或使用clearfix黑客。

0

,你可以把它添加到你的CSS:

#linkDiv { 
    overflow:auto; 
} 

但爲什麼在你的一個標籤不使用inline-block的呢?

a { 
    display:inline-block; 
} 
#linkDiv { 
    border-style:solid; 
}​ 

inline-block的元素,看起來很像左浮動元素,但更像普通內聯元素(這往往是更容易操縱)。適用於所有瀏覽器的IE8 +(並且IE7有一個簡單的polyfill)。

一對夫婦的文章,可能是有用的:

相關問題