简体   繁体   中英

How do I make the flexbox items fit their image size?

The problem is, the images as a whole have to stretch to fit the window as it resizes.

Most of the images work fine but the last one has a different width and it just resizes to a huge size.

It has to be position absolute because there is a web canvas underneath.

I think I tried everything, all the flex-grow, flex-basis stuff. I don't get it.

As you can see in the example, the last image should fit heightwise with the others but I cant get it to fit.

http://jsfiddle.net/huvogt3g/

 .container img { width: 100%; } .container { width: 40%; background: #777; } .container2 { width: 12.5%; background: #777; } .myflex { display: flex; position: absolute; } 
 <div class="myflex"> <div class="container"> <img src="https://placehold.it/512x512/000088/ffffff" /> </div> <div class="container"> <img src="https://placehold.it/512x512/000088/ffffff" /> </div> <div class="container"> <img src="https://placehold.it/512x512/000088/ffffff" /> </div> <div class="container2"> <img style="" src="https://placehold.it/64x512/000088/ffffff" /> </div> </div> 

use this flexbox in one line

     <!DOCTYPE html>
<html>
<head>
<style> body{margin:0;}
.flex-container { 

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row;
  flex-flow: row;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.flex-item:nth-of-type(1) { flex-grow: 1; }
.flex-item:nth-of-type(2) { flex-grow: 1; }
.flex-item:nth-of-type(3) { flex-grow: 2; }
.flex-item4:nth-of-type(4) { flex-grow: 1; }
.flex-item {
    background-color: cornflowerblue;
    width: 40%; 
}
.flex-item 4{
    background-color: cornflowerblue;
    width: 10%; 
    margin: 10px;
}
.flex-item img{
    width: 100%;    height: 100%;
}.flex-item4 img{
    width: 100%;    height: 100%;
}
</style>
</head>
<body>

<div class="flex-container">
  <div class="flex-item"> <img src="https://placehold.it/512x512/000088/ffffff" /></div>
  <div class="flex-item"> <img src="https://placehold.it/512x512/000088/ffffff" /></div>
  <div class="flex-item"> <img src="https://placehold.it/512x512/000088/ffffff" /></div>  
  <div class="flex-item4">  <img style="" src="https://placehold.it/64x512/000088/ffffff" /></div>  
</div>

</body>
</html>

If you want to give all time images the same height, simply add display: flex; to your .container and .container2 classes.

Here's a demo:

http://jsfiddle.net/huvogt3g/1/

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