How can I make a div element match the height of an image and overflow without relying on

Here is the code that I am currently working with: https://codepen.io/allen-houng/pen/ExYKYdq

Additionally, you can find a gist of the code snippet below:

<div class="parent">
 <div class="imageWrapper">
  <img class="image" src="imageurl" />
  </div>
  <div class="textWrapper">
   ...lots of text
  </div>
</div>

The parent container utilizes flexbox and has two children - imageWrapper and textWrapper. Is there a way to make the textWrapper div match the height of the image when scrolling, in case the content exceeds the height (without relying on javascript)?

Expected output screenshot: https://i.sstatic.net/xgDmo.png

Actual output screenshot: https://i.sstatic.net/IBFE4.png

Answer №1

To start, apply .parent with display: flex to ensure equal height columns.

Next, for the column inside .textWrapper, add

overflow: auto; position: relative
.

Include a child element .inner-text with position: absolute;.

.parent {
    display: flex;
}

.textWrapper {
    position: relative;
    overflow: auto;
}

.textWrapper .inner-text{
    position: absolute;
}

Here is a complete example:

.parent {
    width: 620px;
    display: flex;
}

.imageWrapper {
    width: 100%;
    flex: 1;
}

.image {
    width: 100%;
    display: block;
    background: linear-gradient(red, yellow, green);
    height: 205px;
}

.textWrapper {
    flex: 1;
    background: purple;
    color: white;
    position: relative;
    overflow: auto;
}

.inner-text {
    position: absolute;
}
<div class="parent">
    <div class="imageWrapper">
        <img class="image" />
    </div>
    <div class="textWrapper">
        <div class="inner-text">
            The inner text here...
        </div>
    </div>
</div>

Answer №2

For optimal layout control, consider using grid to evenly separate elements of the same size within a parent container that adjusts based on their dimensions. You can then apply overflow: scroll to one child while leaving the other unaffected, allowing the parent to adjust only to the image.

.parent {
   display: grid;
   grid-template-columns: 1fr 1fr;
}

img {
   width: 100%;
}

.text-wrapper {
   overflow: scroll;
}

If you need to crop images to a consistent size regardless of their original dimensions, use this CSS style:

img {
   object-fit: cover;
   object-position: 50% 50%;
}

Adjust the parent container's size accordingly:

.parent {
   height: 600px;
}

Answer №3


It seems that achieving the desired outcome with solely CSS is not feasible. Asynchronous loading of elements on a webpage typically results in images being loaded after text, making it challenging to control the height of a div based on an image load event.

To address this issue, one possible workaround involves using background-image for the div and setting a fixed height for the text content.

.parent {
  position:relative;
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-height:100vh;
}

.image {
  border:1px solid purple;
  background-size:contain;
  background-repeat:no-repeat;
  background-position:center center;
}
.textWrapper {
  height:300px;
  max-height:100vh;
  overflow: auto;
  background-color:purple;
  color:white;
}

https://codepen.io/kriskys/pen/bGbpGqm

Another approach is to adjust the text size dynamically when the image has finished loading using JavaScript:

     $('img').on('load',function(){
       // Create dummy image to get real size
       $("<img>").attr("src", $(img).attr("src")).load(function(){
         var realWidth = this.width;
         var realHeight = this.height;
         $('textWrapper').style({'height':realHeight});
       });
     });   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting several sticky titles after displaying and hiding elements

Inspired by a popular codepen example, I have successfully implemented sticky titles in my sidebar. However, when integrating these sticky titles with the functionality to show/hide related items on click, I encountered some unexpected issues. The code sni ...

Retrieving the value of an array from a JSON data structure

I am working with the object shown below to extract the desired output. The result will be a new object that represents the final output. var data = { Customer: { Name: "emp1", Departments: [ {Departme ...

An error occurred while trying to access properties of null during a promise, specifically when trying to read the 'parentNode' property - triggered by calling router.push({})

After updating my dependencies, I encountered an issue every time I clicked on a button to navigate to the next page. The error message Uncaught (in promise) TypeError: Cannot read properties of null (reading 'parentNode') would appear, even thou ...

What sets the target property of the mousewheel event apart from other events like click, mousedown, and touchstart?

The mousewheel event's target property reveals the DOM element currently being hovered over when using the mousewheel or gesture-capable touchpad. In my experience (specifically in Safari 6, I will verify this in other browsers later), the target ret ...

Issues persist with $.getJSON

I apologize if this question has been addressed previously, but I couldn't find the answer I was seeking. My issue involves using $.getJSON to send variables to a PHP file. Although the file returns success as true, it always triggers the .fail functi ...

Applying CSS classes to my div element

Check out the following code snippet: <div class="page-template-default logged-in"></div> I am trying to apply a class like this: .page-template-default .logged-in { } However, it doesn't seem to work. Any idea why? ...

Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair: { "example": [ { "firstName": " ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Accessing JSON data from the Public folder in a create-react-app

I have a JSON file called ipAddress.json with the following content: { "ipAddress": "11.111.111.111" } To access this file, I placed it in an "ipAddress" folder within the public directory. So now the path is "public/ipAddress/ipAddress.json". However, ...

How many addresses are stored in the JSON file?

After verifying the JSON data and trying to determine the number of addresses, I encountered the following result when accessing the information: var location = req.body; The output obtained was: { AddressValidateRequest: { '-USERID': &ap ...

Using AJAX, FLASK, and JavaScript to send an existing array to an endpoint

Having trouble POSTing the array songFiles generated by the getTableData() function (inside an ajax request) to the /api/fileNames endpoint, and then handling it in the postFileNames() callback function. Any assistance or alternative approaches would be gr ...

What is the most effective method to convert PHP data into JSON and present it in the jQuery success scenario?

In the realm of jQuery, I have this particular piece of code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type ...

Vue.js: Utilizing async/await in Vue.js results in an observer being returned

Currently, I'm attempting to retrieve data from an API and store it in an array. The issue arises when I try to log the response data from the API - the data is displayed just fine. I assign the value of a variable to the data obtained from awaiting t ...

Imitation of three-dimensional camera rotation

I've been exploring the realm of creating 3D games using JavaScript and HTML's 2D canvas. I recently came across a helpful tutorial that guided me in setting up a basic interactive scene. Now, I'm facing a challenge in implementing the func ...

AngularJS fails to fetch data from API queries

Currently facing a challenge with retrieving API data in my AngularJS project. The code below successfully fetches the data and logs it on the console as an array, but I am unable to access and utilize it in the front-end. Please note that the placeholder ...

`CSS alignment problems with multiple images`

Recently, I delved into the world of CSS and HTML. I created an application with pages designed using these languages. Here are the images representing my pages: and the second one is the user page, which serves as the home page. Below is a snippet of my ...

How to Properly Adjust the Material UI CircularProgress Size

Is there a way to display the Material UI CircularProgress component at a size that nearly fills the parent div, which has an unknown size? Ideally, I want the size to be around 0.8 * min(parent_height, parent_width). I've experimented with adjusting ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

JQuery will only run after the Alert has been triggered in Firefox

I am currently facing an issue with updating the 'like' count in my database using the 'changeRating()' method when a user interacts with local like, Facebook like, or Twitter buttons. Oddly enough, the 'likes' are not being ...