Automatically adjust the size of child divs to evenly distribute the width of the parent container

Imagine you have a parent container with a fixed width of 320px and the desire to let users add as many child elements as they want, all resizing automatically to fit the parent's width.

The goal is to maintain the parent div's width without any scrolling overflow, just having the child divs adjust proportionally.

For example,

If there is one child, it should take up 100% width. If there are two children, each should take up 50% width, and so on.

How can this be achieved?

I've tried various CSS approaches but couldn't find a solution. I suspect JavaScript might be needed, but my skills aren't sufficient for that. However, if a CSS-only solution exists, that would be ideal.

Thank you in advance.

(Note: The child divs will be text-free, with only background color and fixed height)

Sample code:

CSS

.box {
margin: 10px;
background: white;
border-radius: 6px;
border: 1px solid darken(white, 12%);
-webkit-box-shadow: 0px 1px 4px rgba(50, 50, 50, 0.07);
-moz-box-shadow:    0px 1px 4px rgba(50, 50, 50, 0.07);
box-shadow:         0px 1px 4px rgba(50, 50, 50, 0.07);
float: left;
}

.line {
height: 6px;
opacity: 0.4;
-moz-opacity: 0.4;
filter:alpha(opacity=4);
margin-bottom: -1px;
float: left;
}

HTML

...

<div class="box">
<div class="line">&nbsp;</div>
</div>

...

#will be able to add any amount of .lines

Answer №1

To achieve equal-width columns, apply the display: table property to the container and use table-layout: fixed with a fixed width if needed. Also, make sure to use display: table-cell for the child elements.

Answer №2

Hope this information proves useful!

<html>
<body>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script tye="text/javascript">
function adjustChildSize( $div ){
    var $children = $div.children(".child");    
    var $count = $children.length; 
    var $width = $div.width(); 
    var $cellwidth = Math.floor( $width / $count ); 
    $children.width( $cellwidth ); 
}

function addNewChild( $div, $html ){
    $( $html ).prependTo ( $div ); 
    adjustChildSize ( $div ); 
}

$(document).ready( function(){
    $("#add").click( function(){ 
        addNewChild( $(".parent"), '<div class="child">Random...</div>' );
        return false;
    });
});
</script>

<style type="text/css">
.parent {
    width: 500px;
    border: 1px solid #000;
}

.child {
    float: left;
}
</style>

<div class="parent" style="width: 500px;">
    <div class="child">Random...</div>
<br clear="all" /></div>
<a href="#" id="add">Add DIV</a>

</body>
</html>

Answer №3

In order for certain browsers to display a DIV with a height below 1em, it may also be necessary to include the rule font-size:0px. Otherwise, the default height will be set to 1em.

UPDATE

As I was in the process of writing my response, additional information became available. If the table layout is functioning correctly, then the answer to the previous comment applies. I have removed the portion of my initial response related to positioning, as it was based on a misunderstanding of your question.

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

Filtering JSON array objects based on multiple attributes using JavaScript

I'm currently facing some challenges with a VueJS application that involves filtering API responses based on multiple dropdown values. So far, I've been able to handle two filters by declaring one outside the if (filtered) statement and the seco ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

Ways to adjust the visibility of the table of contents based on varying screen sizes

I am currently using a JavaScript code to dynamically generate a table of contents from H2 tags, and it's working flawlessly. However, I would like the table of contents to have a status of "Hide" (requiring clicking on "Show" to display the table of ...

What is the best way to generate a hyperlink that will open a raphael graph in my own browser?

If I have a web page that includes a raphael.js drawing in <div id='my-canvas'></div> <body> <div id='part_one'>...</div> <div id='my-canvas'></div> <div id='part_thre ...

Transforming Canvas Images: Resizing, Skewing, and Dragging with Ease

I have a vision for an application that allows users to upload images and manipulate them by dragging the corners to distort the image. However, I am at a loss on where to begin and can't seem to find any examples to guide me. In the meantime, here i ...

Limitations on accessing Google Charts

Every day, consistently, and after a period of usage, Google Charts suddenly stops loading on my ANGULAR project. Currently, I am in development mode with my project running on localhost. When I check my Browser console, it displays the following error me ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Adjust the position of the object in relation to its current orientation

I am facing a challenge in moving an object upwards in relation to its current direction. I am working with a CubeGeometry that has a specific height, and my goal is to place an object at the top of it and have it rotate along with the cube. Simply adding ...

Using several v-for loops within a single Vue component file

I am attempting to populate a table with data fetched from my API using three for loops. const events = await app.$axios.get('/api/events/') const markets = await app.$axios.get('/api/markets/') const runners = await app.$axios.g ...

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

Asynchronously retrieving results in MongoDB

My task involves fetching all users from the users collection. app.post('/login', function(req,res,next){ users = self._db.get('users', {}) }) Below is the function in my database class: this.get = function( col, opt ) { ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Utilizing Facebook's UI share URL parameters within the Facebook app on mobile devices

Encountering an issue with the Fb ui share functionality on certain smartphones Here is the function: function shareFB(data){ FB.ui({ method: 'share', href: data, }, function(response){}); } Implemented as follows: $urlcod ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

Are there any disadvantages to utilizing bindActionCreators within the constructor of a React component when using Redux?

I have come across numerous instances where the bindActionCreators function is used within the mapDispatchToProps function as shown below: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: som ...

Ways to resolve the issue with TypeError: CSS2Properties lacking an index property setter for '0'

I'm currently working on application development using ReactJs and Material UI. When I try to open the application in Mozilla Firefox, an error message pops up saying "TypeError: CSS2Properties doesn't have an indexed property setter for ' ...

What is the best way to delete HTML classes that were generated by a function?

Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

Effective Ways to Segregate CRUD Endpoints in Node.js with Express

When you wish to consolidate all CRUD operations for your model into one file, it is typically done using the following structure as shown in our first method: routes.js const express = require("express"); const users = require("../routes/users"); module ...

Ways to retrieve the data from promises after they have been resolved?

I'm struggling to retrieve the values from getPeople(0,4). function getPeople(start, end) { const peopleArray = []; for (let i = start; i <= end; i++) { peopleArray.push( axios.get(`https://www.testsite.net/api/test/workers/ ...