【问题标题】:Fit an image in a paragraph to width of grandparent div使段落中的图像适合祖父母 div 的宽度
【发布时间】:2015-10-20 02:32:12
【问题描述】:

我觉得这应该很容易,但我已经玩了很长时间了,还没有成功。

我有一个 div,其中的图像设置为 width: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;
}

【问题讨论】:

    标签: html css


    【解决方案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;
    }
    

    【讨论】:

    • 谢谢。不幸的是,它没有做我想要的。我可能应该更清楚,但我无法更改 HTML - 如果可以,我只需将 img 放在 p 标签之外。情况是这是一个 Joomla 模板,我需要作者能够轻松添加自己的图像。
    • 试试这个:jsfiddle.net/q8Lb7t3t/6 如果这对你有用,那么我会更新我的答案。但我建议找到一种方法来更改 html。该标记将难以维护
    • 效果很好,谢谢阿卜杜勒!如果您将此添加到您的答案中,我会打勾:)
    猜你喜欢
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多