2015-10-20 42 views
2

我覺得這應該很容易,但我一直在玩它很多年,並沒有得到任何地方。在一段中適合祖父母的寬度div

我有一個div,裏面的圖像被設置爲寬度:100%。這可以像你期望的那樣工作,並且圖像在div內邊緣出現。

對於這個div內的段落,我有填充。

我想要的是,這些段落中的圖像也出現在div的整個寬度(而不是段落,由於填充而變窄)。不過,我需要保持填充,因爲我需要它或文本。

HTML(不能更改)

<div id="grandparent"> 
    <img src="whatever" /> 
    <!-- this next image should be exactly the same width as the first one --> 
    <p><img src ="whatever" /> This text still needs to be padded though.</p> 
</div> 

CSS:

p { 
    padding:15px; 
} 
img { 
    width:100%; 
} 

我曾嘗試加入負利潤率的圖像(使用CSS下面),它可以將它轉換到邊緣,但我無法準確地將它與div的寬度相同。

CSS:

p img { 
    /*starts the img in the right place, but doesn't fix the width */ 
    margin-left:-15px; 
    margin-right:-15px; 
} 

回答

1

一件事你可以做的是使用的CSS屬性calc。嘗試下面的代碼。請記住,calc在某些較舊的瀏覽器中不起作用。

小提琴:http://jsfiddle.net/q8Lb7t3t/6/

HTML

<div class='gp'> 
    <img src='http://www.online-image-editor.com//styles/2014/images/example_image.png'/> 
    <p> 
     <img class='img-pad' src='http://www.online-image-editor.com//styles/2014/images/example_image.png'/> 
     text text text text text text text text text text 
     text text text text text text text text text text 
     text text text textext text text text text text text 
    </p> 
</div> 

CSS

.gp { 
    width: 300px; 
    background-color: #eee; 
} 
img { 
    display: inline-block; 
    width: 100%; 
    height: auto; 
} 
.img-pad { 
    margin-left: -20px; 
    width: calc(100% + 40px); 
} 
p { 
    padding: 20px; 
} 
+0

感謝。不幸的是它沒有做我想做的事。我可能應該已經更清楚了,但我無法更改HTML - 如果我可以這樣做,我只需將img放在p標籤之外即可。情況是,這是一個Joomla模板,我需要作者能夠輕鬆添加自己的圖像。 –

+0

試試這個:http://jsfiddle.net/q8Lb7t3t/6/如果這對你有效,那麼我會更新我的答案。但我建議找到一種方法來改變HTML。這個標記將很難保持 –

+0

完美的作品,謝謝阿卜杜勒!如果你添加到你的答案,我會給它一個答案:) –

相關問題