如何将div适配到图片大小?

5

我有一个在 div 中的流体图像,在图像下方还有一个带文本的 div。是否可能让 #text 的 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


那么最终的目标是什么——将文本置于图像中心还是使div和图像大小相同?此外,您是否愿意使用jquer / javascript? - reggaemahn
我认为你可能会像这样做 >>> http://jsfiddle.net/HUsRm/10/ - Bhojendra Rauniyar
6个回答

5

由于#container相对定位,您可以绝对定位#text,以防止它拉伸#container

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

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

当然,这也会防止垂直拉伸,并且不会将后续内容向下推。这可能是不想要的?


1

你可以通过只有这个CSS来使它工作:

#container
{
    display:table-caption;
}

Fiddle


实际上,在IE10中,这看起来很糟糕 :( 不过我依然希望能够解释一下是什么让这段代码“工作”的。 - 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

这是您的fiddle链接。您只需要为文本div指定位置即可。

#text {
    position:absolute;
}

1
你现在只是在刷声望,对吧?看看xec的回答。 - Mr. Alien

0

这里是关于JSFIDDLE的答案
你需要在你的<div id="text">..</div>中添加position:absolute

这是你应该应用的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;
}

这是在图像底部的顶部部分,而不是按照问题中指定的“在图像下方”。 - xec

0
我建议您使用适当的标签:figurefigcaption,无论如何,这里有一个干净的解决方案,也适用于您的标记,您可以在此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>

我建议您查看这篇博客文章以获得更好的图像调整。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接