Make the divs inside the parent element grow to occupy the available space, while ensuring they do

I need to set specific minimum and maximum values for the width and height of left-floated divs and make them expand to fill the parent element (body). I am curious if there is a way to achieve this using CSS, or if I should resort to JavaScript.

When you resize the window, you will see empty space on the right of the divs until there is enough space for more divs to fit in. My goal is to have all the divs expand to occupy the empty space until they reach the maximum size, at which point additional divs will adjust based on the number in each row.

In essence, I want these divs to always stay within the specified minimum and maximum widths and heights while flexibly adjusting to fill the entire width of the body.

Here's the sample code:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <style>
      .imageitem {
        background-color: blue;
        margin: 0 5px 5px;
        min-width: 200px;
        min-height: 200px;
        max-width: 250px;
        max-height: 250px;
        float: left;
      }
    </style>
  </head>
  <body>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
    <div class="imageitem"></div>
  </body>
</html>

Answer №1

What you're inquiring about is actually a somewhat intricate layout, although it primarily involves responsiveness. Essentially, the goal is to have two divs that expand to fill the screen (similar to cells in a table) and then have a third div move up into the row once the screen width reaches a certain point.

It's impossible to achieve both the specified dimensions and fill the screen at all widths, as mentioned by Clark. For instance, at 505 pixels wide, two divs will fit with 5 pixels of gap between them. Three divs won't fit until the width reaches at least 610 pixels, leaving a gap where the divs won't completely fill the screen.

Using Media Queries is likely the best approach for this scenario, but the margin may need to be defined as a percentage rather than a fixed pixel value like 5 (unless using jQuery or a similar solution).

A modified version of Clark's answer can be found in this fiddle http://jsfiddle.net/UHqWF/2/

body {
    background:#edeee6;
}

.imageitem {
    -moz-box-sizing:border-box;
 -webkit-box-sizing:border-box;
         box-sizing:border-box;
    float:left;
    max-width:250px;
    min-width:200px;
    padding:5px;
    width:100%;
}

    .imageitem div {
        background:#4e84a4;
        max-height:250px;
        min-height:200px;
    }

@media all and (min-width:420px) {
    .imageitem {
        width:50%;
    }
}

@media all and (min-width:630px) {
    .imageitem {
        width:33.33333%;
    }
}

@media all and (min-width:840px) {
    .imageitem {
        width:25%;
    }
}

@media all and (min-width:1050px) {
    .imageitem {
        width:20%;
    }
}

However, the layout can be a bit jumpy as explained earlier.

An alternative solution would be to remove the width restrictions (eliminating occasional gaps on the right), like shown here http://jsfiddle.net/UHqWF/3/

body {
    background:#edeee6;
}

.imageitem {
    -moz-box-sizing:border-box;
 -webkit-box-sizing:border-box;
         box-sizing:border-box;
    float:left;
    padding:5px;
    width:100%;
}

    .imageitem div {
        background:#4e84a4;
        min-height:200px;
        text-align:center;
    }

@media all and (min-width:420px) {
    .imageitem {
        width:50%;
    }
}

@media all and (min-width:630px) {
    .imageitem {
        width:33.33333%;
    }
}

@media all and (min-width:840px) {
    .imageitem {
        width:25%;
    }
}

@media all and (min-width:1050px) {
    .imageitem {
        width:20%;
    }
}​

Another option is to center the extra space rather than having it at the edges, showcased here http://jsfiddle.net/UHqWF/4/

body {
    background:#edeee6;
}

.imageitem {
    -moz-box-sizing:border-box;
 -webkit-box-sizing:border-box;
         box-sizing:border-box;
    float:left;
    padding:5px;
    width:100%;
}

    .imageitem div {
        background:#4e84a4;
        max-width:250px;
        margin:0 auto;
        min-height:200px;
        text-align:center;
    }

@media all and (min-width:420px) {
    .imageitem {
        width:50%;
    }
}

@media all and (min-width:630px) {
    .imageitem {
        width:33.33333%;
    }
}

@media all and (min-width:840px) {
    .imageitem {
        width:25%;
    }
}

@media all and (min-width:1050px) {
    .imageitem {
        width:20%;
    }
}​

Answer №2

I developed a unique jQuery plugin that takes advantage of CSS3 columns in modern browsers while gracefully falling back to floated columns for older browsers like IE 9 and below.

When resizing, the items maintain their aspect ratio to provide a smooth transition. While achieving a completely fluid look may be challenging, the transition appears relatively smooth depending on the browser being used.

The plugin offers various customizable settings, all of which are well-documented within the code.

To implement the plugin, simply use the following code:

$('#container').adjustColumns({/* options*/});

My goal in creating this plugin was to facilitate the learning process for both CSS3 techniques and fallback methods. I am more than willing to offer assistance and support for using this plugin.

Check out the DEMO: http://jsfiddle.net/SbvGJ/show/

Answer №3

Firstly, ensuring a minimum width of 200px and a maximum width of 250px:

  • For screen sizes between 750px and 800px, there will be a gap ranging up to 50px
  • For screen sizes between 500px and 600px, the gap can extend up to 100px
  • For screen sizes between 250px and 400px, the gap might reach up to 150px

This is just how the layout calculations work out.

If you are comfortable with that, consider using media queries.

You could implement something like this in your CSS:

.imageitem {
    background-color: blue;
    //I've simplified by setting margin to 0.
    //You may need to adjust margin calculations or revise HTML structure for margins
    //Consider using an inner div with a margin instead
    margin: 0px;
    min-width: 200px;
    min-height: 200px;
    max-width: 250px;
    max-height: 250px;
    float: left;
}

@media all and (max-width: 250px) and (min-width: 200px) {
    .imageitem {
        width: 100%;
    }
}

@media all and (max-width: 500px) and (min-width: 400px) {
    .imageitem {
        width: 50%;
    }
}

@media all and (max-width: 750px) and (min-width: 600px) {
    .imageitem {
        width: 33%;
    }
}

@media all and (max-width: 999px) and (min-width: 800px) {
    .imageitem {
        width: 25%;
    }
}

@media all and (max-width: 1249px) and (min-width: 1000px) {
    .imageitem {
        width: 20%;
    }
}

If you also require height resizing, create similar queries for min-height and max-height. Ensure to set the height on the html, body selector as well.

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

Changing the $scope value in one controller based on the input from a

I'm facing an issue with updating my side menu items based on user data. I have a side menu controller where I need to display the username, and in another controller where I retrieve user data from the database and want to update the menu items accor ...

Send the output of an asynchronous ajax request to the designated function within the jQuery Validation plugin

Utilizing the jQuery Validation plugin (JVP) for server-side validations via ajax has been seamless, except for one hitch: JVP struggles with performing remote validation on blank fields. While it's easy to use its default required: true rule for sim ...

Obtain the JSON data from the body of the current post request in Express.js

I have been working on retrieving the actual request body JSON in express.js but haven't been successful so far. Most of the resources I found online only show how to access the body of type ReqBody, whereas I am looking for a way to retrieve the actu ...

Text flickering unexpectedly during hover animation in Bootstrap

Encountered a peculiar issue where dark colors flicker during animation. Link to codepen Adding -webkit-backface-visibility: hidden partially resolves the problem, but it also affects font appearance by making it tighter and brighter. This issue is obser ...

Is there a way to position two images using CSS, with one in the upper right corner and the other in the lower right corner?

I'm trying to use CSS to align two images, one in the upper right position and the other in the lower right position. Can you help me with this? Below is the HTML markup: <th class="X" scope="col"> Time <input id="ORAAsc" class="up" type="i ...

"Enhance User Experience with Multilevel Dropdowns in Bootstrap 4 - Submenus Aligned to the Top

I recently embarked on a project that involved using Bootstrap 4.4, The project is an eCommerce grocery store with departments comprising categories and subcategories. The main menu became very lengthy when using the default code, so I encountered some al ...

Develop a PHP polling system with a limit of one vote allowed per unique IP address

My website features an Ajax Poll where users can vote multiple times after refreshing the page, with results being recorded. However, I want to restrict voting to once per IP address and show the results upon page refresh. Below is the code: The HTML Pag ...

Tips for avoiding cropped images on mobile websites:

I recently created a website that looks perfect on desktop but appears cropped on mobile devices. The site in question is doc.awsri.com Here are the images causing the issue: https://i.stack.imgur.com/eRJXU.png The problem arises when viewing it on a ph ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

React and Redux experiencing issues with rendering the view

Currently, I am in the process of creating a compact bookkeeping application using React and Redux. However, I am facing an issue where the view is not rendering, and there are no errors being displayed in the code. Let's take a look at the structure ...

What measures can be taken to avoid the entire page from reloading?

Within my page, there exist two containers. The first container is designated for displaying a list of items, while the second container showcases actions corresponding to each item. A feature allows me to add a new item dynamically to the first container ...

I am interested in updating the color of the navigation bar displayed on this website

I am having some trouble with manipulating the appearance of - Specifically, I'm struggling to change the color of the black bar at the top to blue. I have scoured the CSS files and examined the HTML, but I can't seem to locate the relevant code ...

Do you have any tips for locating a misplaced jQuery element?

Currently, I am utilizing jQuery.validate and exploring its "success" option, which allows a function to be executed upon valid input on a form. The function takes an argument named "label," which seems to be a dynamically generated label positioned next t ...

How to implement flexslider on a separate page within your Woocommerce website

I've successfully displayed a product on my homepage using the following shortcode: <?php echo do_shortcode('[product_page id="195"]');?> The product is shown with its main image and small thumbnails below it, and on the rig ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

How can I implement Before() and After() hooks within a hooks.js file for a Selenium and JavaScript project?

Within my Selenium JS / Cucumber framework, I have incorporated Before() & After() functions to handle the setup and tear down of my webdriver. To manage these functions, I decided to organize them in my customSteps.js file alongside other cucumber st ...

Innovative HTML5 Video Canvas Shapes

I'm currently working on creating a circular frame or canvas for live HTML5 Video. While I am able to round the corners using keyframes radius property, it results in an oval shape rather than a circle. My preference would be to utilize a div object ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

Switching a set of checkboxes with a main checkbox

I've got this JS code that's doing its job and satisfying all my requirements when one of the checkboxes at the top is checked. However, I'm struggling to uncheck them by following the same process (unchecking the first box is not possible). ...