What is the best way to adjust the width of floating divs to completely fill the space they occupy?

On the first picture, there are six equal divs displayed. As the screen size increases, the width of the divs also grows to fill up their space, like a table cell or another div. If there is enough space in the first row to accommodate the fourth div, it shifts there (as shown in the second picture). After this adjustment, the divs return to their initial width (as seen in the first picture). In the second row, it is necessary for two divs to be centered.

Is it possible to achieve this task using only HTML+CSS? Or does it require JavaScript as well? How can this be done? Thank you for any assistance.

First picture:

* * * *   * * * *   * * * *
*     *   *     *   *     *
*     *   *     *   *     *
* * * *   * * * *   * * * *

* * * *   * * * *   * * * *
*     *   *     *   *     *
*     *   *     *   *     *
* * * *   * * * *   * * * *

Second picture:

* * * *   * * * *   * * * *  * * * *
*     *   *     *   *     *  *     *
*     *   *     *   *     *  *     *
* * * *   * * * *   * * * *  * * * *

          * * * *   * * * *
          *     *   *     *
          *     *   *     *
          * * * *   * * * *

index.html

<link rel="stylesheet" type="text/css" href="style.css">

<div class="clearfix">                          
    <div class="outer-div">
        <div class="inner-div">
            <div class="floating-div">Float 1</div>
            <div class="floating-div">Float 2</div>
            <div class="floating-div">Float 3</div>
            <div class="floating-div">Float 4</div>
            <div class="floating-div">Float 5</div>
            <div class="floating-div">Float 6</div>
        </div>
    </div>
</div>

style.css

.clearfix { width: 30%; height: 100px; border: 1px solid}
.outer-div { position: relative; float: right; right: 50%; }
.inner-div { position: relative; float: right; right: -50%; }
.floating-div {  float: left; margin: 10px; border: 1px solid red; }

Adjust the browser zoom setting to see the effect. The desired outcome may not be visible immediately. http://jsfiddle.net/TYK3J/4/

Answer №1

There are multiple approaches to achieve this, but one effective method is to utilize a media query targeting the elements container based on device dimensions. Once the media query triggers, you can style the container to center all divs using properties like text-align: center.

HTML

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
    </div>
  </body>
</html>

CSS

.container{
  width: 615px;
}

.square{
  display: inline-block;
  background: pink;
  width: 200px;
  height: 200px;
}

@media only screen and (min-width : 716px) {
    .container{
      width: 995px;
      text-align: center;
    }
}

See it in action here: http://plnkr.co/edit/K7SWAKj4wdjpeLaTwH4e?p=preview

Answer №2

Using floating won't achieve this result, as floating is meant to align elements left and right within inline text blocks.

A more modern approach involves using the display: inline-block attribute on the boxes and centering them with text-align: center in the container. This method requires some clever tricks to maintain precision. To make the boxes fill the available space, CSS media queries can be used to adjust the number of boxes per row based on the available space (e.g., 25% width per box for four boxes in a row starting from 720px).

I suggest setting up a jsfiddle to test this solution – we are available to provide further guidance if needed.

Additionally, a cutting-edge solution would involve utilizing flexboxes; while not widely adopted among web developers yet, browser compatibility is steadily improving.

On another note, since you mentioned JavaScript in your post, I would caution against that approach. However, there are libraries like masonry designed for creating intricate grid layouts.

Answer №3

In order to keep the 3 divs inline, you will need to wrap them with a container element like .row from the bootstrap css framework.

Example of CSS styling:

.container { width: 100%;}
.container > div {
    width: 32%;
    display: inline-block;
    min-height: 50px;
}

Check out the fiddle for a live demo: http://jsfiddle.net/michasko/6yVQL/

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

What is the best way to dynamically display CSS code from a PHP variable without needing to refresh the

I am working on a page that utilizes ajax and PHP for all functions. Within the tab content, users have the option to select colors using color pickers. Once a user saves their chosen colors, I store the new CSS code in the database. The CSS code is as ...

Transferring information to React (Native) hooks in a way similar to how it is done

Transitioning to Hooks in React Native has been a new learning curve for me, especially when it comes to passing data to child elements. In the past with class-based components, passing props was as simple as using XML-style syntax. A Simple Example using ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

There has been a mistake: The module '.... ode_modules erser-webpack-plugindistindex.js' cannot be found. Please ensure that the package.json file contains a correct "main" entry

After setting up Vue.js and executing npm run serve, I encountered the following error: PS C:\Amit\Demo\VUEDemo\myvue> npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f5e1eeedfdd8a8b6 ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

Empty POST request detected in select2 form submission

Looking for some assistance to help steer me in the right direction. My professor is unable to provide guidance. I'm currently struggling with handling POST requests in my form for select2 multiple fields. The issue arises from a Yes/No flag that dete ...

What is the process for implementing a Content Security Policy to enable the loading of external JS files from a CDN in ExpressJS?

When working with ExpressJS, the HTML file is loaded in the following manner: app.use(express.static(__dirname + '/src/templates/')); Within the HTML file, here is an example of a meta tag containing Content Security Policy: <meta http-equiv= ...

Cursor disabling effect in IE 11 causing interference with drop-down options on Twitter Bootstrap 3

Right above a disabled twitter bootstrap 'form-control' input element sits a drop-down list. <div> <select> <option> Option 1 </option> <option> Option 2 </option> <option> Op ...

CSS stylized horizontal navigation bar completed

* { border: 0px; margin: 0px; padding: 0px; } body { background-color: #FFC; } #wrapper { width:70%; margin: 0% auto; } #header { background-color: #C1D1FD; padding: 3%; } #nav { clear:both; padding: auto; position:inherit; background-color:#F0D5AA; wid ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

Discovering the true width of elements that have overflow hidden in IE7 using jQuery

I am dealing with a dynamic list that contains around 50 elements, but the exact number may vary. <div style="width:465px;"> <ul> <li>aaa</li> <li>aaa</li> <li>aaa</li> <li>aaa& ...

Utilizing the Bootstrap grid system allows for input fields to automatically expand to 100% width once they reach

I am encountering some challenges while attempting to develop a responsive form using bootstrap grids. The issue seems to arise when resizing the browser window, as the grid classes behave unexpectedly by expanding and taking up the entire page width at ce ...

Here is a guide on how to ensure that the div elements automatically fill the available space

Looking at this html page: Check out the jsFidlle Demo here I am aiming to have the boxes fill up the space effortlessly, each with equal width but varying heights. This is similar to the layout in Google Keep notes ...

Adjusting Header Size While Scrolling in Angular

Looking for assistance with AngularJS regarding handling events (specifically scrolling). I am trying to dynamically change the size of the header based on whether the user scrolls up or down. Below is a snippet of JavaScript code that achieves this effect ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

Display the progress bar's completion percentage during animation

Creating a progress bar using HTML with the following structure: <div class="progressbar"><div class="text">%0 Completed</div> <div class="progressbar_inner"></div> </div> Implemented jQuery code fo ...

What is preventing me from accessing the JSON return values in my .NET MVC project?

I've been stuck on this seemingly minor issue for hours now. Every time I look at the console, it's showing 500 errors and nothing is coming up in alerts. It appears that the Json() function isn't working as expected. I even tried setting a ...

Is there a way to verify if an email is already registered within a MERN stack application

I am in the process of creating a registration form and need to verify if an email already exists within the system. Below is the React code snippet showcasing the structure for better understanding. In the schema, emails are defined as unique. AuthContr ...

A method for dynamically enlarging a parent node within a dhtmlx tree using JSON data

As I was browsing through the dhtmlx documentation, I came across this particular method: This method determines how the server-side URL is constructed when making dynamic loading calls: <script> tree.setXMLAutoLoadingBehaviour(mode); </s ...

Tips for altering the color of the email text as it is being typed into the input field

Is it possible to customize the text color while typing email in an input field? <form action=""> <input type="email" name="mail" id="" placeholder="Your Email"& ...