0

I have a section with two containers, a text container and an img container. The text container's height changes when I open the details list (which I want), but I can't get the image to resize as well, while keeping a 50/50 width. Both containers are 50vw.

    <section>
        <div class="textContainer">
            <details>Long list of content</details>
        </div>
        <div class="imgContainer">
            <img src="" alt="">
        </div>
    </section>

I want the height of the section to be fit-content based on the content of the textContainer, and the textContainer to be fit-content, based on its content (obviously). HOWEVER I want the image's height to be the same as the textContainer, when the details is closed and when it is open.

Any suggestions?

Oh and I've got 9 of these sections, each with different length of text content.

I've tried fiddling with max-height/max-width on the image. Tried a bunch of object-fits and even tried with some JS.

img.setAttribute = ("height", textBox.offsetHeight)

But I always get the result on this image:

required format

greybeard
  • 2,249
  • 8
  • 30
  • 66

1 Answers1

0

To resize an image in HTML based on the size of a neighbouring element that may change dynamically, you can make use of CSS and a little bit of JavaScript. Here's an example of how you can achieve this:

HTML:

<div class="container">
  <img id="image" src="your-image.jpg" alt="Your Image">
  <div id="neighboring-element">Neighboring Element</div>
</div>

CSS:

.container {
  position: relative;
}

img#image {
  max-width: 100%; /* Ensure the image does not exceed the container width */
  height: auto; /* Preserve the aspect ratio of the image */
}

#neighboring-element {
  /* Your styles for the neighboring element */
}

JavaScript:

window.addEventListener('resize', function() {
  var containerWidth = document.querySelector('.container').offsetWidth; // Get the width of the container
  var image = document.getElementById('image');
  image.style.width = containerWidth + 'px'; // Set the width of the image to match the container
});

In this example, the JavaScript code adds an event listener to the window's resize event. Whenever the window is resized, it retrieves the width of the container element and sets the width of the image accordingly. By using the max-width CSS property for the image, we ensure that the image won't exceed the container's width.

Make sure to replace "your-image.jpg" with the actual path to your image, and customize the CSS styles as needed for your design.

  • Thank you for the answer! Can i use the resize eventlistener on an element? The text box changes height, and i want the image to change height with it – NikolajHB Jun 12 '23 at 13:36
  • I think you can refer to this article for that solution : https://stackoverflow.com/questions/6492683/how-to-detect-divs-dimension-changed – Shelly Thakur Jun 13 '23 at 07:24