2013-07-05 65 views
5

我有一個div內的流體圖像,在圖像下面還有一個帶有文本的其他div。 #text div可以像圖片一樣大小嗎?如何使div適合圖像?

<div id="container"> 
    <img src="http://dummyimage.com/300x200/c7c1c7/fff.jpg"> 
    <div id="text">Several standard dimensions are included in dummyimage.com including ad sizes and screen resolution sizes.</div> 
</div> 


#container { 
    display: inline-block; 
    height: auto; 
    max-width: 100%; 
    position: relative; 
} 

img { 
    max-width:100%; max-height:100%; 
} 

FIDDLE

+0

那麼,什麼是終極目標 - 文本居中在圖像或有div和圖像大小相同?另外,你會願意使用jquer/javascript嗎? –

+0

我認爲你可能會這樣做>>> http://jsfiddle.net/HUsRm/10/ –

回答

0

Here is the answer on JSFIDDLE
您需要添加一個position:absolute<div id="text">..</div>

這裏是CSS,你應該申請:

#text{ 
    position:absolute; 
    bottom:0;left:0; 
    width:100%; 
    background:#444; 
    color:#FFF; 
    text-align:center; 
    font-size:11px; 
    line-height:14px; 
    padding:2px 0; 
} 
+0

這是圖像底部*的頂部*,而不是圖像*下的問題中指定的*。 – xec

0

試試這個FIDDLE

#container { 
    display: inline-block; 
    height: auto; 
    max-width: 100%; 
    position: relative; 
} 

img { 
    max-width:100%; max-height:100%; 
} 
#text{ 
    max-width:300px; 

} 
+1

謝謝,但如果我不知道圖像的大小? – user25381

+0

您的圖像尺寸(http://dummyimage.com/300x200/c7c1c7/fff.jpg) – falguni

+0

尺寸不是固定的圖像,所以也許400,500 .. – user25381

5

看到作爲#container相對定位,您可以定位#text絕對,以防止拉伸#container

#text { 
    /* remove from flow, prevents from stretching container */ 
    position: absolute; 
} 

http://jsfiddle.net/HUsRm/5/

這當然會,也防止縱向拉伸,而不是按以下內容下來。這可能是不需要的?

0

這是您的fiddle link。你只需要給文本div一個位置。

#text { 
    position:absolute; 
} 
+1

雅現在你只是代表耕種,不您?閱讀什麼[xec](http://stackoverflow.com/a/17484641/1542290)回答了 –

1

您可以通過只有這個CSS使這項工作:

#container 
{ 
    display:table-caption; 
} 

Fiddle

+0

其實,這在IE10中看起來很可怕:(我仍然喜歡解釋什麼讓這段代碼「工作」,儘管 – xec

0

我會建議你使用正確的標籤:figcaption,反正這裏是一個乾淨的解決方案,也可以與您的標記,你可以看到在這個FIDDLE結果。

figure, #container { 
      display: table; 
      max-width: 100%; 
      width: auto !important; 
      } 

     img { 
      display: table-row; 
      max-width: 100%; 
      width:100%; 
     } 

     figcaption, #text { 
      display: table-caption; 
      max-width: inherit; 
      caption-side: bottom; 
      word-wrap: break-word; 
     } 

    <!--[if lt IE 9]><style type="text/css"> 
    img, 
    figcaption { 
     width: auto !important; 
    } 
    </style><![endif]--> 
    <figure> 
     <img src="http://dummyimage.com/300x200/c7c1c7/fff.jpg" alt="alt text" /> 
     <figcaption>Several standard dimensions are included in dummyimage.com including ad sizes and screen resolution sizes.</figcaption> 
    </figure> 
<!-- YOUR MARKUP #2 --> 
    <div id="container"> 
     <img src="http://dummyimage.com/300x200/c7c1c7/fff.jpg" alt="alt text" /> 
     <div id="text">Several standard dimensions are included in dummyimage.com including ad sizes and screen resolution sizes.</div> 

    </div> 

我還建議調整到看一看this blog post美好形象