2014-12-03 65 views
0

我試圖在div中包裝圖像,但div由父div進行擴展。如何在圖像上打包div?

<div id="parent" style="display: inline-block; position: relative; text-align:center"> 
    <div id="wrapper"> 
     <img> 
    </div> 
    <p>Some text that expands the wrapper div more than image width</p> 
</div> 

該文本字段擴展父div比圖像更寬,這也擴大了包裝div。我如何讓包裝div與img的尺寸完全相同?

img也沒有包裝沒有邊距或填充,但包裝div比圖像更寬。

+0

你有什麼其他的CSS? – 2014-12-03 09:15:38

+2

'div's是塊元素,因此它們將佔用其父項的全部寬度。嘗試將'wrapper'設置爲'display:inline'或'float:left',具體取決於您希望顯示的方式。 – Rhumborl 2014-12-03 09:16:56

+0

@Firze在#wrapper上顯示:inline-block。 – Gezzasa 2014-12-03 09:21:14

回答

3

使用display:inline-block上#wrappper

DEMO

+0

哦。我很確定我已經嘗試過,但顯然我沒有。謝謝。我現在覺得很愚蠢。 – Firze 2014-12-03 09:19:33

+0

@Firze我喜歡給元素添加邊框,以便我可以看到到底發生了什麼。希望你會嘗試我的方法。 :) – 2014-12-03 09:20:46

+0

如果'display:inline-block'不起作用,請嘗試使用'display:inline'。 – 2017-05-18 06:35:15

0

您需要設置display:inline-block wraper元素

<div id="parent" style="display: inline-block; position: relative; text-align:center"> 
    <div id="wrapper" style="display: inline-block;"> 
     <img src="https://cdn2.iconfinder.com/data/icons/picol-vector/32/source_code-128.png" />   
    </div>  
    <p>Some text that expands the wrapper div more than image width</p> 
</div> 

如果你想保持p大小相同的圖像,你需要使用一些JavaScript或jQuery的

eg

$('#parent').css({ 
    maxWidth: $('img').width() 
}); 

Fiddle