关于html:如何将div的宽度设置为其同级img的宽度

How to set the width of a div equal to the width of its sibling img

我有这样的HTML代码:

1
2
3
4
      <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>

我希望页脚的宽度与其兄弟img的宽度相同,无论图像的宽度如何。图像的宽度将根据所包含的图像而有所不同,但我希望页脚的宽度与图像的宽度完全相同。
我尝试了以下方法:

1
2
3
4
5
6
7
.card {
   display: inline-block;
}
.card-content {
   display: flex;
   flex-direction: column;
}

但是如果页脚比图像宽,则会加宽img。这不是我想要的。我希望页脚的宽度取决于图像的宽度,而不是相反。

请帮助我。感谢您提前提出建议。


由于图像和页脚都位于同一个div中,没有其他同级,因此它们可以轻松地共享具有card-content类的父div的相同宽度。

只需添加

1
2
3
4
5
6
7
img{
width : inherit;
}

footer : {
width : inherit
}

小提琴:https://jsfiddle.net/qo6e9882/1/


添加max-width。希望它也足以以相同的宽度查看元素

1
2
3
4
5
.card-content  {
  display: flex;
   flex-direction: column;
max-width:480px;
}

为此,您可以在父元素上使用display: table并设置width: 1%

1
2
3
4
5
6
7
.card-content {
  display: table;
  width: 1%;
}
footer {
  background: lightgreen;
}
1
2
3
4
    <img src="http://placehold.it/480x320">
    <footer>
      Some text here that makes the width of this footer greater than the width of sibling img tag.
    </footer>


试试这个

1
2
3
4
5
6
7
8
9
10
11
12
13
$(document).ready(function(){

    var x = $(".card-content > img").width();
    var y = $(".card-content > footer").width();
   y =  x;
    if(y == x) {
       $(".card-content > footer").css("width", x);
      }
  else{
      alert("na");
    }
   
});
1
2
3
4
5
6
7
8
.card {
   display: inline-block;
}
.card-content {
    display: flex;
    flex-direction: column;
 
}
1
2
3
4
5
6
7
8
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">


   
      <img src="http://searchengineland.com/figz/wp-content/seloads/2015/10/google-panda-name3-ss-1920-800x450.jpg" width=480px height=320px>
      <footer>
        Some text here that makes the width of this footer greater than the width of sibling img tag.
      </footer>