Div adjusts its height to match another div's, regardless of the latter's size

I'm currently working on a website where I have a list of news displayed in divs. Each div contains two inner divs: an image on the left and the title, date, and the first 30 words of the news on the right. I am looking to make the image div adjust its height based on the text div, regardless of the image size or aspect ratio. I want to achieve this without using fixed dimensions to ensure responsiveness. I am using Bootstrap 3.3.7 for this project.

You can view an example of my current progress.

Below is the HTML code I have:

<!-- First News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4  news-img-div">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>

Here is the CSS I have used for visualization purposes:

.news-img-div {
  background-color: red;
}
.news-text-div {
  background-color:aqua;
}

I have added background colors to the divs for better visualization. Please expand the result tab to ensure the image and text are displayed on the same row.

Is there a way to achieve this using only CSS? Alternatively, I am open to solutions involving JS.

Answer №1

To achieve the desired layout, apply the following CSS to the parent div that contains the two child divs (with the class container-fluid):

display: flex;

By using this CSS property, the image div will automatically adjust its height to match the height of the text div, which in turn matches the height of the container.

Check out the updated version of your code with the modifications implemented: jsFiddle

Additional Update

Upon further review, it appears that the previous solution does not fully meet your requirements.

Your specific preference is for the image div to always have the same height as the text div.

Here is an alternative solution using pure JavaScript:

The provided JavaScript code dynamically adjusts the height of each image div to match the height of its corresponding text div. Additionally, the code handles responsiveness by recalculating the heights upon window resize.

Enhanced Edit

Based on your feedback,

You mentioned that the images become disproportionate from the text div as the screen size changes.

To address this issue, I have refined the code to maintain consistency between the image and text div heights. The adjustHeight function now ensures proper alignment between the elements, triggered both on page load and window resize events for optimal responsiveness.

To enhance efficiency, a scheduling mechanism has been incorporated to manage the frequent resize events efficiently while maintaining the desired layout.

Answer №2

Since you've included jQuery in your post tags, I have a potential solution for you to consider.

http://jsfiddle.net/yLyv9fyx/3/

Alternatively, you can also refer to the code snippet below. Please note that the reported Script Error may be due to cross-domain script sourcing for bootstrap, but corrections are welcome:

$(".news-img-div").each(function() {
  var textDivHeight = $(this).parent().find("div.news-text-div").height();
  $(this).height(textDivHeight);
  var imgHeight = $(this).find("img.img-responsive").height();
  if (imgHeight > textDivHeight) $(this).find("img.img-responsive").height(textDivHeight);
});
.news-img-div {
  background-color: red;
}

.news-text-div {
  background-color: aqua;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<!-- First News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4  news-img-div">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>

UPDATE:

There have been some enhancements made in the code snippet below. However, it seems you already have a working solution: http://jsfiddle.net/yLyv9fyx/5/

Here is the updated JavaScript code:

function updateImgDiv() {
    $(".news-img-cont").each(function() {
        var textDivHeight = $(this).parent().find("div.news-text-cont").height();
        $(this).height(textDivHeight);
        var imgHeight = $(this).find("img.img-responsive").height();
        if (imgHeight>textDivHeight) $(this).find("img.img-responsive").height(textDivHeight); 
    });
}
updateImgDiv();
$( window ).resize(function() {
    updateImgDiv();
});

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

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Rearranging HTML elements using jQuery

I have a collection of 5 HTML elements <a href="#"><img src="image1.jpg" /></a> <a href="#"><img src="image2.jpg" /></a> <a href="#"><img src="image3.jpg" /></a> <a href="#"><img src="image4.j ...

Eslint was unexpectedly unable to detect any errors in the .ts files

After creating a SvelteKit project with npm create svelte@latest, I included some .ts files for a particular library. However, when running eslint ., it fails to detect any errors. The default eslint config generated from Svelte is as follows: .eslintrc. ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

Rows with an ambiguous number of horizontal lines

I am looking to create multiple rows that are horizontally floated, as shown in the image. However, I am facing an issue with setting the width of the container because I do not know the exact number of rows that will be added. Currently, my code looks li ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

Identifying whether a child component is enclosed within a specific parent using React

Is there a more elegant and efficient method to determine if the parent of SeminarCard is Slider? Currently, I am passing this information through a prop. The prop value (true/false) is used to provide additional padding. When used independently: <Semi ...

Safari and iOS 15 to 14 have rendered the Javascript audio context unusable

Recently, I noticed that the IOS/Safari upgrade has caused some issues with the web audio API. Check out this simple code that used to work on IOS and Safari before the upgrade, but now it doesn't work anymore. Interestingly, it still works on Firefo ...

In what way does ReactJS enable me to utilize constant functions before they are declared?

I'm intrigued by the concept of using a value before defining it in ReactJS. Let's explore this through an example: function CounterApp() { const [counter, setCounter] = useState(0); const increaseValueTwice = () => { increaseValue() ...

Clicking an AngularJS button within a form is causing an unexpected page refresh

I am facing an issue with adding a new input field on click. I have two buttons, one to add and another to remove the input box. When I click on the add button, it should add a set of input boxes, but currently, it only adds one and refreshes the page, dis ...

Utilizing Sessions Across Several PHP Forms

Hey there! I've got a query for you. When you kick off your PHP code with session_start(), do you need to keep adding the prior variables on subsequent form pages? I'm contemplating using the session() function for my GYM Sign UP Webpage. The f ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Angular 13's APP_INITIALIZER doesn't wait as expected

Recently, I have been in the process of upgrading from okta/okta-angular version 3.x to 5.x and encountered an unexpected bug. Upon startup of the application, we utilized APP_INITIALIZER to trigger appInitializerFactory(configService: ConfigService), whi ...

Displaying JavaScript array contents in an HTML page without using the .innerHTML property

As someone new to the world of JavaScript and web development, I find myself faced with a challenge. I want to showcase the contents of two different JavaScript arrays in an HTML format. However, my research has led me to believe that utilizing .innerHTML ...

Tips for displaying the date in 13-digit Unix Timestamp format using JSpreadSheet

I am faced with a challenge involving data that is stored in Unix Timestamp format, which I need to display as a readable date (e.g. YYYY/MM/DD) in JSpreadSheet ("jspreadsheet-ce"). Currently, the data appears as a 13-digit number and looks unattractive. ...

Concealing the WordPress sidebar specifically for mobile phones, excluding iPads, tablets, and other devices

I currently have Google AdSense displayed in the sidebar of my website, but it appears distorted when viewed on a mobile phone. My objective is to eliminate the sidebar when the site is accessed via a mobile device, while maintaining it for all other devic ...

How to properly adjust image size in a flex-direction column layout - tips and solutions

My mission is to place an <img> with text blocks above and below it inside a container of specified height. The exact heights of the text blocks and image are unknown. After extensive searching, my colleague provided a useful solution by using the ...

Validating file extensions using Jquery during file uploads

I'm working on a page where users can upload images using drag and drop, but I want to limit them to uploading only jpg files. Unfortunately, my knowledge of jquery is quite basic, so I'm struggling to figure out how to achieve this. Here's ...

The jQuery function appears to be running multiple times in a loop

For some reason, every value in my JSON object is getting added to the "listOfCountries" array twice. It seems like there might be a loop going through the result object more than once. I could really use some assistance with this issue! var listOfCountri ...

The process of automating e-signature input with Selenium

Is there a way to automate e-signature input in Selenium? I attempted using the action class to draw a line on the canvas object. Below is the code I used: Actions actionBuilder=new Actions(driver); Action drawOnCanvas=actionBuilder ...