Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep this example more generalizable for others, I'm using placeholder numbers instead of actual database values (for instance, assigning the value 5 to a variable called 'levmax'). The main issue I'm encountering is aligning all the created divs next to each other. Most alignment examples I've found focus on HTML-created divs rather than those generated through JavaScript.

The code is functioning as intended, except for the part where the divs need to be laid out horizontally. The code includes around 80 lines, but my primary concern is achieving proper div alignment. Here's the existing script:

<html>
<head>
<script>
var lev = 0; 
var levmax=5;
var count = 0;
function addBu(){
        lev++;
        var bo = document.getElementById("kod");
        var di = document.createElement('DIV');
        for (var i=0; i<3; i++){
            var bu= document.createElement('BUTTON');  
            var te = document.createTextNode('Text');
            if(lev===1){
            bu.addEventListener("click", novo);
            }
            var te1 = document.createTextNode(lev.toString());
            var br = document.createElement('BR');
            bu.id=lev.toString();
            bu.appendChild(te);
            bu.appendChild(te1);
            di.appendChild(bu);
            di.appendChild(br);
            count++;
        }

        bo.insertBefore(di, bo.childNodes[0]); 
};

function novo(){
    if(lev===1){
        lev++;
        var bo = document.getElementById("kod");
        var di = document.createElement('DIV');
        for (var i=0; i<4; i++){
            var bu= document.createElement('BUTTON');  
            var te = document.createTextNode('Text');
            var te1 = document.createTextNode(lev.toString());
            var br = document.createElement('BR');
            bu.addEventListener("click", repeat);
            bu.id=lev.toString();
            bu.appendChild(te);
            bu.appendChild(te1);
            di.appendChild(bu);
            di.appendChild(br);
            count++;
        }

        bo.insertBefore(di, bo.childNodes[0]); 
    }
    function repeat(){
        if(lev<levmax){
            lev++;      
            var bo = document.getElementById("kod");
            var di = document.createElement('DIV');
            for (var i=0; i<2; i++){
                var bu= document.createElement('BUTTON');  
                var te = document.createTextNode('Text');
                var te1 = document.createTextNode(lev.toString());
                var br = document.createElement('BR');
                bu.addEventListener("click", repeat);
                bu.id=lev.toString();
                bu.appendChild(te);
                bu.appendChild(te1);
                di.appendChild(bu);
                di.appendChild(br);
                count++;
            }   
            bo.insertBefore(di, bo.childNodes[0]); 
            var le=(lev-1).toString();
            document.getElementById(le).removeEventListener("click", repeat);
        }
    }

}
</script>
</head> 
<body id="kod" onload="addBu()">
</body>
</html>enter code here

<head>
<script>
var lev = 0; 
var levmax=5;
var count = 0;
function addBu(){
        lev++;
        var bo = document.getElementById("kod");
        var di = document.createElement('DIV');
        for (var i=0; i<3; i++){
            var bu= document.createElement('BUTTON');  
            var te = document.createTextNode('Text');
            if(lev===1){
            bu.addEventListener("click", novo);
            }
            var te1 = document.createTextNode(lev.toString());
            var br = document.createElement('BR');
            bu.id=lev.toString();
            bu.appendChild(te);
            bu.appendChild(te1);
            di.appendChild(bu);
            di.appendChild(br);
            count++;
        }

        bo.insertBefore(di, bo.childNodes[0]); 
};

function novo(){
    if(lev===1){
        lev++;
        var bo = document.getElementById("kod");
        var di = document.createElement('DIV');
        for (var i=0; i<4; i++){
            var bu= document.createElement('BUTTON');  
            var te = document.createTextNode('Text');
            var te1 = document.createTextNode(lev.toString());
            var br = document.createElement('BR');
            bu.addEventListener("click", repeat);
            bu.id=lev.toString();
            bu.appendChild(te);
            bu.appendChild(te1);
            di.appendChild(bu);
            di.appendChild(br);
            count++;
        }

        bo.insertBefore(di, bo.childNodes[0]); 
    }
    function repeat(){
        if(lev<levmax){
            lev++;      
            var bo = document.getElementById("kod");
            var di = document.createElement('DIV');
            for (var i=0; i<2; i++){
                var bu= document.createElement('BUTTON');  
                var te = document.createTextNode('Text');
                var te1 = document.createTextNode(lev.toString());
                var br = document.createElement('BR');
                bu.addEventListener("click", repeat);
                bu.id=lev.toString();
                bu.appendChild(te);
                bu.appendChild(te1);
                di.appendChild(bu);
                di.appendChild(br);
                count++;
            }   
            bo.insertBefore(di, bo.childNodes[0]); 
            var le=(lev-1).toString();
            document.getElementById(le).removeEventListener("click", repeat);
        }
    }

}
</script>
</head> 
<body id="kod" onload="addBu()">
</body>
</html>

Answer №1

To achieve this layout using CSS, we can set the width, padding, and float properties for the containing <div> with a class name of .item:

.item {
  width: 300px;
  padding: 20px;
  float: left;
}

This will align all <div> elements with the class name of "item" side by side.

Alternatively, you can use Bootstrap to create a similar layout. Here's an example:

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="db-item col-md-4">

            </div>
            <div class="db-item col-md-4">

            </div>
            <div class="db-item col-md-4">

            </div>
        </div>
    </div>
</body>

You can also utilize your JavaScript skills to dynamically insert a new

<div class="row"></div>
every three items to maintain the desired layout.

Answer №2

If you want to create a flexible layout, consider using flex-box.

/*Styles for the container div*/
.flex_container {
   display: flex; /*Transforms the div into a flexible container*/
   flex-flow: row wrap; //Shortcut for specifying flex-direction and flex-wrap
   /*Add other styles here…*/
}

/*Styles for individual flex items*/
.flex_item {
  /*Define your custom styles here*/
}

To learn more about using flex-box, check out this guide.

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

Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should beco ...

How to position Angular Component at the bottom of the page

I have been working on my angular application and recently created a footer component that I want to stay at the bottom of the page like a typical footer. The footer component is included in the default app.component.html file, which makes it visible on th ...

What is the best way to format table values as currency?

Still getting the hang of Javascript, and I'm in the process of learning... Currently, my challenge involves calculating the total sum of values within a Bootstrap 4 table and formatting the result as currency (specifically in USD format). While I&ap ...

Can you explain the distinction between ' &:hover' and ' & :hover' pseudoclass selectors?

While styling a Material-UI Button, I encountered an unexpected behavior when adding hover effects. When using & :hover, only the inner span of the button was affected. However, when using &:hover, the desired style was achieved. What is the diff ...

The ng-view directive appears to be missing in the AngularJS framework

I am attempting to create a route using AngularJS, but when I launch my application, the ng-view does not display anything. I am new to AngularJS. index : <!DOCTYPE html> <html lang="en"> <head> <title>CRUD</title> </ ...

identifying the :hover state of a link that has a distinct ID

If I were to have the code as follows: .nav > li.dropdown.open.active > a:hover and I needed to target the same style for a link 'a' with the unique id #futurebutton, what would be the correct syntax? Would it not be?: .nav > li.d ...

Steps for transforming an array of arrays into a JSX element within a React component, where each nested array contains its own clipPath

The array_groups variable consists of an array containing multiple arrays. Each inner array holds the coordinates of regular circles that are closely spaced together. The intention is to clipPath these inner circle arrays as a whole. When the mouse hovers ...

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...

Using ngForm to implement multiselect options in HTML

Attempting to implement a multiselect dropdown that is tied to a dynamic property receiving data from a JSON script via service. Successfully displayed the data in the dropdown, but encountering abnormalities when adding the multiple attribute within the s ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

Switching over a function from jQuery to Mootools

Here is a snippet of code used to refresh a specific DIV by making a request for data. The current function works as intended, but we are looking to migrate to Mootools. JavaScript Code: <script> jQuery.noConflict(); (function(jQuery) { jQuery ...

Clarifying the confusion surrounding AngularJS $q, promises, and assignments

Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - http://plnkr.co/edit/ZK ...

I'm attempting to make the button hover color transparent, but unfortunately, it's not having any effect

Check out the code snippet below. I'm attempting to adjust the button hover color to transparent. The div class is "button_container" while the button class is "btn". I made changes to the color initially, but it doesn't seem to be working. Any a ...

Tips for customizing Material-UI Switch button appearance

Is there a way to remove the box-shadow on the thumb of the Switch button when it's disabled? I've tried various methods like adding the box-shadow in the switchBase and removing it from the thumb, but it affects the parent element as well. Anoth ...

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...

Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution: My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I' ...

Get the value of the button that has been clicked

I have a query regarding building a website that can be started via PowerShell. The PowerShell HTML code I am using is: $proxys = "" foreach ($email in $ADObj.proxyAddresses){ $proxys += "<button id='$email' name='alias&apo ...

Code in JavaScript that shows only a portion of the selected option in a dropdown menu

I'm just starting to learn Javascript and I'm looking to create a script for a select tag that displays countries and their phone codes. My goal is to have the dropdown menu show both the country and code, but once the user selects an option, onl ...

Is it possible for a CSS code to be universally effective across all PHP files by setting style.css in header.php and then including header.php in each of the other PHP files?

Let me confirm, the code snippet from the header.php file is as follows: <link rel="stylesheet" href="style.css"> If I include the following code in every other php file: include 'header.php'; Will all the files have access to style.css ...

What could be the reason for the <div> style on the webpage not changing?

I'm currently working on a Django project where I've encountered a challenge. I have div containers with dynamic IDs, where the ID is fetched from the database and automatically injected into the HTML. Here's an example of how the dynamic I ...