Home > Net >  Make two elements the same width, show them next to each other as long as it fits, otherwise show th
Make two elements the same width, show them next to each other as long as it fits, otherwise show th

Time:08-04

Here is a fiddle that accomplishes the desired result with Javascript:

https://jsfiddle.net/ykczmqpg/

<style>
    .container {
      width: 400px;
      border: 1px solid red;
      margin-bottom: 15px;
      text-align: center;
    }

    .item, .info {
      display: inline-block;
      text-align: left;
    }
</style>

<div class=container>
  <div class=item>
    <img src="http://placekitten.com/150/150">
  </div>
  <div class=info>
   This text is supposed to have the same width as the image. Until 2x the width of
   the image does not fit into the container. So here it should be on the right side of the image.
  </div>
</div>

<div class=container>
  <div class=item>
   <img src="http://placekitten.com/300/50">
  </div>
  <div class=info>
   This text is supposed to have the same width as the image. Until 2x the width of
   the image does not fit into the container. So here it should be below the image.
  </div>
</div>

<script>
 imgs = document.querySelectorAll('img');
 for (img of imgs)  {
  img.onload = e=> {
    info = e.target.parentNode.parentNode.querySelector('.info');
    w = e.target.width "px";
    console.log(info);
    info.style.width = w;
  };
 }
</script>

Is that possible without Javascript, only with CSS?

I tried with flex, but to no avail so far.

CodePudding user response:

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

p {
  width: 200px;
  height: 200px
}
<div >
  <img src="https://unsplash.it/200/200">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book..</p>
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap

CodePudding user response:

Wrap both containers in new and on that div you can use display:flex and flex-wrap: wrap

  • Related