Setting the width of a parent div tag in CSS based on its children tags

My goal is to have a parent div tag with several children div tags placed horizontally. Since the number of children tags is not known in advance, I cannot set the width of the parent div tag using CSS alone, so I am using JavaScript for this purpose.

var cnt = $("#parent div").length; // Get total count of children tags
var parent_width = cnt * 102 ;  // Calculate parent tag width based on children tag width and borders

$("#parent").css({
    width: parent_width+"px"
});

<div id="parent" style="height: 100px; background-color: #090">
    <div style="height: 100px; width: 100px; background-color: #009; border: 1px solid #ccc; float: left">
    </div>
    <div style="height: 100px; width: 100px; background-color: #009; border: 1px solid #ccc; float: left">
    </div>
</div>

While the current solution works, I believe there might be a way to achieve this layout without using JavaScript, relying solely on CSS. Can someone please guide me on how to do this?

Answer №1

Solution:

HTML

<div id="container">
    <div></div>
    <div></div>
    <div></div>
</div>​

CSS

​#container {
    display: flex;
    justify-content: space-around;
}

#container​ > div {
    height: 100px; 
    width: 100px; 
    background-color: #009; 
    border: 1px solid #ccc; 
}​

Result: http://jsfiddle.net/xyz123/

Answer №2

To ensure the children fit into the parent element, apply the following CSS to the parent:

#container
{
  background-color:#090;
  height:100px;
  float:left;
}

This will automatically adjust the width of the parent div to accommodate its children.

Additionally, remember to set the float property on the child div elements if you want them to align in the same line.

Answer №3

Use inline-block for display property.

If you need help, I can assist you with it.

To implement this in your project, apply the following CSS to the parent element:

#container {
    height: 100px; 
    background-color: #090;
    display: inline-block; 
}

#container > div {
    height: 100px; 
    width: 100px; 
    background-color: #009; 
    border: 1px solid #ccc; 
}
<div id="container">
    <div></div>
    <div></div>
    <div></div>
</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

Transformations in Object Attributes Following an AJAX Submission

For my latest project, I am developing an application using node.js and express. One of the functionalities involves making a POST request that sends an array of strings to the server. However, upon inspecting the request body on the server side, I noticed ...

The currentViewData property of the model is not defined, resulting in a TypeError when implementing the Hierarchical Grid and accessing the Child Grid

I'm currently working on implementing a Hierarchy Grid in ASP.Net MVC using Syncfusion Grid Control. During the process of fetching data from the server side with an ajax call for the expansion of the child grid, I encountered a JavaScript error (Type ...

Invoking a REST API synchronously using JavaScript

I am just starting out with JavaScript and the npm ecosystem. I am attempting to upload data to my REST service using a POST call. The data is being fetched from a CSV file, which is going well so far. For each line of data that is fetched, I convert it as ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

Developing tabbed sections in XSLT

Utilizing Angular JS within XSLT, I am aiming to develop a tab-based user interface using XML data. The requirement is to generate multiple links and corresponding div elements based on the number of nodes in the XML. To manage the display of these div ele ...

Trigger a Jquery sound when an HTML result is found and displayed

I am using a Jqgrid to display a table. Within the "return" column, along with other data, there is a span element like the following: <span class="return" id="ret0>4.25%</span> My webpage contains multiple instances of these spans: < ...

Oops! There was an issue with the form field - make sure to include a MatFormFieldControl for proper validation on the

I am working on an Angular application that utilizes Angular Material components. Despite conducting extensive research online, I have not been able to find a suitable solution to the specific error message I have encountered. The issue revolves around a ...

What is the best way to refactor the code below?

My goal is to construct a JSON structure using data retrieved from an API call. Utilizing the code below, I am able to generate the structure as desired. Despite this success, I am now seeking advice on how to refactor the code in order to eliminate nested ...

Drag items with jQuery without needing to click on them

I am working on a draggable div and currently using the jQuery UI .draggable function. However, this doesn't quite meet my requirements. $('.magic_background').draggable({ cursor: 'move', containment: &apo ...

Can you clarify the purpose of response.on('data', function(data) {}); in this context?

I am curious about the inner workings of response.on("data"). After making a request to a web server, I receive a response. Following that, I utilize response.on("data" ...); and obtain some form of data. I am eager to uncover what kind of data is being p ...

Checking the Focus of an Element in Vue.js

Below is the code I am working with: <template> <div id="app"> <span contenteditable="true" spellcheck="false" style="width: 800px; display: block" :v-text="textEl&qu ...

Modifying the geometry of a three.js object

I have been working on changing the geometry of objects in a three.js scene. I have written code that almost works, where a mouse click triggers the change. However, I am facing an issue where the shape is only updated on the first mouse click, even though ...

Leveraging entities within entities with connections and seeding data in Nest JS / TypeORM

Imagine we are developing our initial entities for a brand new web application. We start with an entity for users: @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() username: string; @Column() password: string; ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

Exploring custom JavaScript with Construct 2's generated code

How can I access the score of a game user in Construct2 Engine using external JavaScript? Is there a method to achieve this? Appreciate any guidance on this matter. ...

What is the best way to ensure that a task is performed only once the DOM has finished loading following an AJAX request

<div id="mydiv"> ... <a id="my-ajax-link"> ... </a> ... ... <select id="my-selectmenu"> ... </select> ... </div> Upon clicking the 'my-ajax-link' link, it triggers an AJ ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

There seems to be a column in the MySQL INSERT query that is unidentifiable and does not exist in the list of fields

id and cost are required as integers and cannot be left empty. I encountered the following error message: 'Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'' var sql = "INSERT INTO Paintings(` ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle. Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears. How can I keep this default option visible after making a selection? ...