2016-09-25 35 views
1

我有一個包含標題,文本和圖像的列表,有時候,當沒有足夠的文本時,我的列表開始中斷,即。該列表開始嵌套本身。當使用浮動圖像時,HTML列表不是垂直對齊的

<ul> 
    <li><img style="float:left"><h3>title</h3> ... some text here</li> 
    <li><img style="float:left"><h3>title</h3> ... some text here</li> 
    <li><img style="float:left"><h3>title</h3> ... some text here</li> 
</ul> 

我在這裏有一個例子:

http://jsfiddle.net/2z6Zn/246/

img { 
 
    float: left; 
 
    margin-right: 0.1em; 
 
}
<ul> 
 
    <li> 
 
    <h3>photo</h3> 
 
    <img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" />some text next to the photo 
 
    </li> 
 
    <li> 
 
    <h3>photo</h3> 
 
    <img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" />some text next to the photo 
 
    </li> 
 
    <li> 
 
    <h3>photo</h3> 
 
    <img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" />some text next to the photo 
 
    </li> 
 
</ul>

什麼是解決這個問題的最好方法是什麼?

回答

4

您缺少的部分是清除float s。使用這個:

li:after { 
    content: ''; 
    display: block; 
    clear: both; 
} 

現在你將刪除「嵌套」。

注意的是,雖然使用的是浮動的容器,你應該總是clear 他們遵循從而創造出新的塊 格式上下文,因爲它被稱爲下一個容器之前。否則,你會看到 不可預知的行爲。

下面

修訂演示:

img { 
 
    float: left; 
 
    margin-right: 0.1em; 
 
} 
 
li:after { 
 
    content: ''; 
 
    display: block; 
 
    clear: both; 
 
}
<ul> 
 
<li> 
 
<h3>photo</h3> 
 
<img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" /> some text next to the photo 
 
</li> 
 
<li> 
 
<h3>photo</h3> 
 
<img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" /> some text next to the photo 
 
</li> 
 
<li> 
 
<h3>photo</h3> 
 
<img src="http://commons.cathopedia.org/w/images/commons/thumb/f/fe/Carnevale_di_Venezia.JPG/250px-Carnevale_di_Venezia.JPG" /> some text next to the photo 
 
</li> 
 
</ul>

+0

@Erik讓我知道,如果這回答了你的問題...如果需要,將返工...謝謝! – kukkuz

+1

啊,太棒了!謝謝,這會讓我走! –

0

取消已在的jsfiddle即

img { 
    float: left; 
    margin-right: 0.1em; 
} 

而是隻需添加下面的CSS

應用CSS
+0

呃,不,這張照片不會左右浮動。 –

0
/* This will make every element inside Li align in a line */ 

li * { 
    display: inline-block; 
} 
/* have specifically gave h3 element block property so that it can be in a separate line and serve as a heading */ 
    li h3 { 
    display: block; 
    } 

工作小提琴 - http://jsfiddle.net/2z6Zn/247/

+0

請隨時向您的代碼添加一些解釋... – andreas