user4063815
user4063815

Reputation:

How to make img scale in flexbox?

I have this huge image (I know, bad, will be replaced by some smaller ones for different viewport-sizes) that I want to display next to another div. Both elements are inside a flexbox, so flex-items.

See: https://jsfiddle.net/aedtyj9y/

My problem is that the image is way too big. What I would want is the image to take up all the space of #test which itself should only maximum take up 30% of the whole horizontal space, so having 70% of the main class='flex-container' for details and the rest for a an image that is contained in the 30% (preferably cropped instead of scaled)

Sounds easy, right? Just add max-width:30% to #test!

WRONG! https://jsfiddle.net/04wohehh/

Image is still too big.

So what, just add max-width:100%; max-height:100%; to the img itself, right?

Again, not working as intended:

https://jsfiddle.net/wqhtqq8d/

Upvotes: 1

Views: 257

Answers (2)

dippas
dippas

Reputation: 60563

is this what you looking for?

  • set flex: 0 70% in .details
  • set flex: 0 30%; display: flex; align-items: center in #test

html,
body {
  margin: 0;
  padding: 0;
}

#info {
  background-color: #2aabd2;
  max-width: 100vw;
  min-height: 100vh;
}

#info nav {
  max-width: 5%;
}

.flex-container {
  display: flex;
}

main {
  background-color: red;
}

.details {
  flex: 0 70%
}

#test {
  flex: 0 30%;
  background: blue;
  display: flex;
  align-items: center
}

.testimage {
  display: block;
  max-width: 100%;
  background-color: blueviolet;
  box-shadow: 0 0 10vh #111;
}
<section id="info" class="flex-container">
  <nav id="node">
    <ul>
      <li>Home</li>
      <li>Other</li>
    </ul>
  </nav>
  <main class="flex-container">
    <div class="details">
      Blablablablabla
    </div>
    <div id="test">
      <img class="testimage" src="http://placehold.it/2000x2000">
    </div>
  </main>
</section>

Upvotes: 1

user7677469
user7677469

Reputation:

Here is my take: https://jsfiddle.net/hq2ppqr5/

What I did:

  1. Added back in the max-width: 100% and min-width: 100% for img, embed, object, video in order to ensure it the img does not overflow/break out of it's "cage"

  2. Removed margin-left: auto; from #info main as it is unnecessary, flexbox should take care of that!

  3. Added flex-grow:1; to #info main to let it fill up the remaining (horizontal) space!

  4. added flex-grow: 1 to the first child of the section

  5. Added a background-color to the nav

  6. Changed main to section (during fiddling around :))

One note though: it still looks different in firefox and chromium, but this seems to be an issue with padding.

Firefox evenly centers both flex-items, while chromium puts the image at the bottom. I am not sure what exactly is causing this.

Upvotes: 0

Related Questions