Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

css - flex item with image child doesn't adjust its size properly

I found this post, Flex item with image child doesn't adjust from its original width, which I initial thought had the answer, but it didn't, ... well partially it did, when a set height is used.

What I want and expect to happen here, is that the image matches the text element's height and then adjust its width while keeping its ratio.

This appears to work in Chrome, but not in Edge/IE/Firefox. Haven't been able to test Safari as I don't have an iOS device, so I would appreciate if someone can share how/if it work there.

This doesn't need to be a flexbox solution, though I expect a CSS one, meaning no script.


Edit

The given text's height could be dynamic, and based on its content, so the predefined 200px was simply to give it a height, JSFiddle demo, set height .


JSFiddle demo, content based height

Stack snippet

.container {
  display: inline-flex;
}

.img img {
  height:100%;
}

.text {
  background: lightblue;
}

.text-content {
  width: 200px;
}
<div class="container">
  <div class="img">
    <img src="http://placehold.it/160x90">
  </div>
  <div class="text">
    <div class="text-content">
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
      Some text content<br>
    </div>
  </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should define the height at the .container level. Following CSS will work for all the browsers you mentioned above:

.container {
    display: inline-flex;
    height: 200px;
}

.img {
    height: 100%;
}
.img img {
    height:100%;
}

.text {
    background: lightblue;
}

.text-content {
    width: 200px;
}

UPDATE

I'll leave the old answer just in case but this seems to work codepen. I've tried with varying number of lines and text sizes.

.container {
  display: inline-flex;
}

.img img {
  height:100%;
}

.text {
  background: lightblue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...