简体   繁体   中英

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

I have an HTML code like this:

<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>

I want the footer to have the same width as that of its sibling img no matter what the width of image. The widths of images will be different depending upon the images contained but I want the footer to have exactly the same width as that of the image. I have tried the following:

.card {
   display: inline-block;
}
.card-content {
   display: flex;
   flex-direction: column;
}

But it widens the img if the footer is wider than image. This is not what I want. I want the width of footer dependent on the width of image and not the other way round.

Please help me. Thanks for the suggestions in advance.

Since both image and footer are in same div with no other sibling, they can easily share same width of the parent div with class card-content.

Just add

img{
width : inherit;
}

footer : {
width : inherit
}

Fiddle : https://jsfiddle.net/qo6e9882/1/

To do this you can use display: table on parent element and set width: 1% .

 .card-content { display: table; width: 1%; } footer { background: lightgreen; } 
 <div class="card"> <div class="card-content"> <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> </div> </div> 

add max-width . Hope it's also enough to view the element in same width

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

Try this

 $(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"); } }); 
 .card { display: inline-block; } .card-content { display: flex; flex-direction: column; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div class="card"> <div class="card-content"> <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> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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