简体   繁体   中英

CSS/JS Resize figure to fit image size

I experimented a littlebit with transitions and wanted to show a caption for an image on :hover. This is what I got right now:
(I tried to resize the figure itself with the sizes of the image)

 //Resize figure to image size $(document).ready(function() { $("figure>img").load(function() { $(this).parent().width($(this).width()); }); }); 
 figure { display: table; position: relative; overflow: hidden; } figcaption { position: absolute; background: rgba(0, 0, 0, 0.75); color: white; padding: 10px 20px; opacity: 0; /* unvisible to fade in later */ bottom: 0; left: 0; display: none; /* unvisible to fade in later */ -webkit-transition: all 0.6s ease; -moz-transition: all 0.6s ease; -o-transition: all 0.6s ease; } figure:hover figcaption { opacity: 1; /* visible */ left: 0; display: inline-block; /* visible */ } .img-middle { height: 60%; width: 60%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <figure> <img class="img-middle" src="img/test.png" alt="" width="700" height="500"></img> <figcaption>This is a cool caption</figcaption> </figure> 

The figure never was resized.
The problem right now is that the figure somehow has a width of 100% and therefor the :hover effect also triggers somewhere next to the image. I don't want to set the size of the figure manually. And when I tried figure>img:hover figcaption { /* do stuff */ } (to trigger the caption fade in only on image hover) it somehow didn't worked anymore.
So because that dont worked for me, I tried to resize the parent according to its childrens size...

这个数字比我的形象大

is this what you were going for?

 figcaption { position: absolute; display: block; background: rgba(0, 0, 0, 0.75); color: white; height: 100%; overflow: hidden; width: 0; /* unvisible to fade in later */ top: 0; left: 0; /* unvisible to fade in later */ -webkit-transition: all 0.6s ease; -moz-transition: all 0.6s ease; -o-transition: all 0.6s ease; text-overflow: ellipsis; white-space: nowrap; } figure { display: table; position: relative; overflow: hidden; border: 1px solid; /** * only an example */ width: 500px; height: 100px; } figure img { display: block; width: 100%%; height: 100%; } figure > .image-container { width: auto; display: block; width: 80%; margin: 0 auto; } figure > .image-container:hover { width: 100%; } figure > .image-container:hover figcaption { padding: 10px 20px; width: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <figure> <div class="image-container"> <img class="img-middle" src="http://lorempixel.com/400/200/" alt="" width="100%" /> <figcaption>This is a cool caption</figcaption> </div> </figure> 

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