2012-08-16 48 views
0

我正在創建我的第一個博客模板。CSS - HTML:內聯框擴展比預期更大?

我希望像維基百科這樣的內聯圖像旁邊有它的文章的段落。我用下面的代碼實現了這一點:

<div class="photo"> 
    <img src="image_file.jpg"> 
</div> 
div[class='photo'] { 
    margin: 10px; 
    float: left; 
    clear: left; 
} 
img { 
    max-width: 500px; 
    min-width: 150px; 
    margin: 8px; 
} 

所有的工作都很好,直到這一點。不過,我也希望把圖像文件下方的字幕,所以我的

<div class="photo"> 
    <img src="image_file.jpg"> 
    <p>Caption for the image file which might be long</p> 
</div> 

遺憾的是之後推出

標題

,這 <p>使得這張照片DIV擴大比照片本身使它看起來很有趣較大。我希望它的 max-width與照片一樣大,如果文字很大,請轉到第二行或第三行。

我該如何做到這一點?我試過width: auto; display: block;,把<p>放在另一個div裏,但是失敗了。

謝謝你的幫助。

PS。我知道我可以解決這個問題,一旦頁面通過JS加載,但我很想學習如何解決它的正確的CSS方式。謝謝!

+0

ygssoni 2012-08-16 13:33:14

回答

1

試試這個 - DEMO

HTML

<div class="photo"> 
    <img src="image_file.jpg"> 
    <p>Caption for the image file which might be long</p> 
</div> 

CSS

div.photo { 
    margin: 10px; 
    float: left; 
    clear: left; 
    position: relative; 
    background: honeydew; 
} 

div.photo img { 
    max-width: 500px; 
    min-width: 150px; 
    margin: 8px; 
} 


div.photo p { 
    position: absolute; 
    bottom: 12px; 
    left: 10px; 
    right: 8px; 
    background: rgba(0, 0, 0, .4); 
    color: #fff; 
} 
+0

真棒佐爾坦!非常感謝你。所以這裏的關鍵是使p絕對? – Phil 2012-08-16 14:03:12

+0

歡迎你:)是的,你讓它成爲'絕對',然後在家長的位置不超過它 – 2012-08-16 14:05:01

1

如果問題僅僅是該div寬度大於img寬度大,你可以嘗試移動p總分#photo和內外另一div把:

<div class="photoBox"> 
    <div class="photo"> 
     <img src="image_file.jpg"> 
    </div> 
    <p>Caption for the image file which might be long</p> 
</div> 

...然後相應地改變的CSS:

div.photoBox { 
    margin: 10px; 
    float: left; 
    clear: left; 
} 
img { 
    max-width: 500px; 
    min-width: 150px; 
    margin: 8px; 
} 
+0

謝謝! ....... – Phil 2012-08-16 14:03:50