简体   繁体   English

基于图像缩小以适应 div 和段落?

[英]Shrink-to-fit div and paragraph, based on image?

The code below is a simplified version of my website.下面的代码是我网站的简化版本。 On my site, the image width varies from page to page and the text is around 100 words.在我的网站上,图像宽度因页面而异,文本大约 100 个字。 That means the paragraph stretches the DIV to be wider than the image.这意味着该段落将 DIV 拉伸为比图像更宽。 Using only CSS, is it possible to shrink the DIV and the paragraph to the width of the image?仅使用 CSS,是否可以将 DIV 和段落缩小到图像的宽度?

JSFiddle here JSFiddle在这里

Example of what I'm trying to describe here .我试图在这里描述的例子 Top is what I'm getting, bottom is what I want.顶部是我得到的,底部是我想要的。

HTML HTML

<div>
    <img src="image.jpg" />
    <p>Lorem ipsum dolor sit amet.</p>
</div>

CSS CSS

div {
   display: inline-block;
   }

And for doing anything table related I shall forever shame myself: http://jsfiddle.net/WM6hK/3/对于做任何与表格相关的事情,我将永远为自己感到羞耻: http : //jsfiddle.net/WM6hK/3/

div {
display: table;
border: 1px solid red;
width: 1%;
}

p {
border: 1px solid blue;
}​

You can use this:-你可以使用这个:-

    div {
    width:20%;
    display:inline-table;
    }


p {
    border: 1px solid blue;
    }

It will totally work according to image size.....它将完全根据图像大小工作.....

see the demo:- http://jsfiddle.net/WM6hK/11/看演示:- http://jsfiddle.net/WM6hK/11/

You can add a CSS style to the parent div.您可以向父 div 添加 CSS 样式。

set the width of the parent div to width: fit-content.将父 div 的宽度设置为 width: fit-content。

this will make your parent div to shrink or expand based on the size of the child elements nested within it.这将使您的父 div 根据嵌套在其中的子元素的大小缩小或扩展。

 div { width: fit-content; border: 3px solid red; text-align: center }
 <div> <img src="https://picsum.photos/200" /> <p>Lorem ipsum dolor sit amet.</p> </div>

No, it's not possible by only using CSS.不,仅使用 CSS 是不可能的。 You will need to set a width for the parent div and rescale your images.您需要为父 div 设置宽度并重新缩放图像。

I recommend adding in a little jquery.. to make your life so much easier:我建议添加一个小 jquery.. 让你的生活更轻松:

imgw = $("img").width();
$("div").css("width", imgw);

Here is how it would look: http://jsfiddle.net/WM6hK/2/这是它的外观: http : //jsfiddle.net/WM6hK/2/

This way you can add this simple line of code to any div and just replace $("div") with and ID $("#idofdiv").通过这种方式,您可以将这行简单的代码添加到任何 div,只需将 $("div") 替换为 ID $("#idofdiv")。 Hope this helps!希望这可以帮助!

Right now its not possible, using CSS现在不可能,使用 CSS

Using jQuery, its as easy as this使用jQuery,就这么简单

$("div").width($("div img").width());

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM