将段落中的图像调整为祖父素div

时间:2015-10-20 02:32:12

标签: html css

我觉得这应该很容易,但我已经玩了很多年了,还没到任何地方。

我有一个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 个答案:

答案 0 :(得分: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;
}
相关问题