A code snippet designed to ensure uniform height for all floating div elements

Hello, I am facing an issue with resizing 20 left-floated divs of varying heights on my website. Previously, when my website was designed using pixels, a script worked perfectly for resizing them.

However, after switching to a percentage-based design (% design), the script is no longer as reliable and sometimes fails to resize the divs properly.

Could you please review the script and suggest any adjustments needed for liquid layouts?

I'm also wondering if the way I call the script might be causing the problem?

Thank you in advance.

Below is the script:

var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();

function setConformingHeight(el, newHeight) {
 // Save the original height in case it needs to be reverted
 el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
 el.height(newHeight);
}

function getOriginalHeight(el) {
 // Return the originalHeight, if it exists
 return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
}

function columnConform() {

 // Find the tallest DIV in each row and match the heights of all DIVs within that row
 $('div.column').each(function(index) {

  if(currentRowStart != $(this).position().top) {

   // Set all heights on the completed row
   for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);

   // Set variables for the new row
   rowDivs.length = 0; 
   currentRowStart = $(this).position().top;
   currentTallest = getOriginalHeight($(this));
   rowDivs.push($(this));

  } else {

   // Another div on the current row. Add it to the list and check if it's taller
   rowDivs.push($(this));
   currentTallest = (currentTallest < getOriginalHeight($(this))) ? (getOriginalHeight($(this))) : (currentTallest);

  }
  // Handle the last row
  for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);

 });

}

$(window).resize(function() {
 columnConform();
});

$(document).ready(function() {
 columnConform();
});

Answer №1

Switching to a fluid layout (% design) requires adding a window resize listener. This means that when the browser is resized, the script needs to be recalculated with new dimensions. Unlike pixels, which have a fixed size and do not change regardless of screen size adjustments, fluid layouts adapt to varying screen sizes by dynamically adjusting their content.

Answer №2

Here is an example of using styles in a certain way:

<style>
    .container{
        background:#F00;height:300px
    }
    .container div{
        float:left;height:100%;width:33.33%;
    }
</style>
<div class="container">
    <div style="background:#FED"></div>
    <div style="background:#EDF"></div>
    <div style="background:#DFE"></div>
</div>

All you need to do is specify the height of the parent div and the width of the child div

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 your jQuery search scope correctly restricted?

Upon coming across this code snippet, I can't help but wonder if it's merely limiting the scope or selecting both elements simultaneously. container = jQuery("#test", parent.document); jQuery("param[name=scale]", another.object) Would anyone b ...

Leverage ng2-charts along with a loading component during the AfterViewInit lifecycle hook

Currently, I am working on a web page that contains various charts. My focus right now is on developing a simple loader as shown below: <div *ngIf="loading === true; else elseBlock" class="container"> <div class="grid-pulse la-3x"> </di ...

The current Webpack configuration for production fails to account for importing CSS files

I am struggling to figure out how to properly load a static site that is not located in the root folder: let HWPTest = new HtmlWebpackPlugin({ template: __dirname + "/src/artists/test.html", filename: 'artists/test.html', favicon: &apos ...

Issues arising from the combination of two variable values

I'm facing some issues trying to combine two variables and insert them into an ajax post URL. Unfortunately, I keep receiving error messages. Let me share what I have attempted so far: var photoId = 227; var jobId = 334; $.ajax({ type: "POST" ...

Designing a charcoal square div featuring a see-through circular element at its center

I'm working on a design concept that involves creating a square div with a transparent circle in the center. The idea is to have an image as the background, with the transparent circle acting like a window through which the background image can be see ...

What is the best way to achieve maximum clarity in a div element while adjusting opacity?

Is there a way to have a div with an opacity of 40%, but make the text inside the div show with an opacity of 100%? #box { Background-color:#000; Opacity:40%; } ...

When working with React, encountering a "TypeError: is not a function" message from a function prop can

I am a beginner with React and I'm attempting to pass a function as a prop to a child component. In this scenario, the parent component looks like this: const [gameStarted, setGameStarted] = useState(false); const [gameSettings, setGameSettings] = use ...

Only one active class is allowed in the Bootstrap Accordion at any given time

I have implemented Bootstrap's accordion on my webpage, consisting of two different sections with unique content. Upon loading the page, the active class defaults to the first element of the first section. However, if I navigate to the "Second" sectio ...

Choosing the perfect gradient shade for a progress bar canvas illustration: Tips and tricks

I am trying to customize the appearance of the usage bar in my Google Chrome extension by utilizing the features of the HTML5 canvas. Currently, the bar consists of a basic DIV element: <div id="idUsgBar"></div> accompanied by this CSS stylin ...

Methods to disregard class prefix in css document

When I inspect elements in the Chrome console, I notice styles applied to certain divs/buttons like this: /* Sample Chrome browser styles */ .ItemClass1-0-3-171.ItemClass2-0-3-173: { background-color: "red" } I'm wondering how I can def ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...

Converting RowDataPacket to an array in Node.js and MySQL API, learn how to convert a RowDataPacket from the MySQL API into an array

Hello, I need assistance with converting my row data packet into an array of arrays or nested arrays. Please provide code snippet below: router.get('/getPosts/:user_id', (req, res, next) => { connection.query('SELECT * FROM files WHERE ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Conceal anchor links using jQuery by targeting their title attribute

Looking at the html below <li class="static"> <a title="blog" class="static menu-item" href="http://google.com">Blog</a> </li> <li class="static"> <a title="profile" class="static menu-item" href="http://profile.com"> ...

Trigger event once the component has finished construction

I have integrated jqTree into my project following these steps: Adding 'p' elements with the '.root' class dynamically to the page. Calling jqTree for each of the 'p.root' elements when a button is clicked. Adding an id afte ...

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

Tips for showing text on top of a responsive image using CSS

I am working on a layout with 4 columns, each containing images of different sizes followed by a hover effect with an absolutely positioned mask. The width of the mask is currently exceeding the width of the images. Is there a way to ensure that the mask ...

Transfer the script from package.json to an npm package

In each of our plugins' root directories, there is a file named tools.js. This file contains a build function that assists in creating builds for the plugin. The package.json file references it like this: "scripts": { "build:node&qu ...

Is there a way for me to transfer parameters between pages on my website?

Utilizing Jquery along with functions like localStorage.setItem() and localStorage.getItem(), I have been able to transfer parameters from one page to another. However, I am uncertain about how to integrate this functionality into the backend code. For i ...