Html 如何将div的宽度设置为其同级img的宽度

Html 如何将div的宽度设置为其同级img的宽度,html,css,Html,Css,我有如下HTML代码: <div class="card"> <div class="card-content"> <img src="somesource.png" width=480px height=320px> <footer> Some text here that makes the width of this footer greater than the width of sibling

我有如下HTML代码:

<div class="card">
   <div class="card-content">
      <img src="somesource.png" width=480px height=320px>
      <footer>
        Some text here that makes the width of this footer greater than the width of sibling img tag.
      </footer>
   </div>
</div>
但如果页脚比图像宽,则会使img变宽。这不是我想要的。我希望页脚的宽度取决于图像的宽度,而不是相反


请帮帮我。提前感谢您的建议。

要做到这一点,您可以在父元素上使用
display:table
,并设置
宽度:1%

。卡片内容{
显示:表格;
宽度:1%;
}
页脚{
背景:浅绿色;
}

此处的某些文本使此页脚的宽度大于同级img标记的宽度。

要做到这一点,您可以在父元素上使用
显示:表格
,并设置
宽度:1%

。卡片内容{
显示:表格;
宽度:1%;
}
页脚{
背景:浅绿色;
}

此处的某些文本使此页脚的宽度大于同级img标记的宽度。

添加
最大宽度
。希望它也足以以相同的宽度查看元素

.card-content  {
  display: flex;
   flex-direction: column; 
max-width:480px;
}

添加
最大宽度
。希望它也足以以相同的宽度查看元素

.card-content  {
  display: flex;
   flex-direction: column; 
max-width:480px;
}

因为图像和页脚都在同一个div中,并没有其他同级,所以它们可以轻松地和类卡片内容共享父div的相同宽度

加上

img{
width : inherit;
}

footer : {
width : inherit
}

Fiddle:

因为图像和页脚都在同一个div中,没有其他同级,所以它们可以轻松地与类卡内容共享父div的相同宽度

加上

img{
width : inherit;
}

footer : {
width : inherit
}
小提琴:试试这个

$(文档).ready(函数(){
var x=$(“.card content>img”).width();
变量y=$(“.card content>footer”).width();
y=x;
如果(y==x){
$(“.card content>footer”).css(“宽度”,x);
}
否则{
警报(“na”);
}
});
.card{
显示:内联块;
}
.卡片内容{
显示器:flex;
弯曲方向:立柱;
}

此处的某些文本使此页脚的宽度大于同级img标记的宽度。
试试这个

$(文档).ready(函数(){
var x=$(“.card content>img”).width();
变量y=$(“.card content>footer”).width();
y=x;
如果(y==x){
$(“.card content>footer”).css(“宽度”,x);
}
否则{
警报(“na”);
}
});
.card{
显示:内联块;
}
.卡片内容{
显示器:flex;
弯曲方向:立柱;
}

此处的某些文本使此页脚的宽度大于同级img标记的宽度。

我很好奇
flexbox
是否也能做到这一点?@kukkuz我不确定。我很好奇
flexbox
是否也能做到这一点?@kukkuz我不确定。