What's the best way to arrange buttons in a vertical stack?

Currently, I am working on a project that requires stacking multiple buttons on top of each other without any gaps in between. Here is my existing code:

This is the desired outcome:

Can this be achieved using CSS?

The function I am currently using accepts a height and width to create a grid of buttons.

function createBoard (height, width)
{
    for (let h = 0; h < height; h++)
    {
        for (let w = 0; w < width; w++)
        {
            let button = document.createElement('button');
            button.setAttribute('class', 'pixel');
            document.body.appendChild(button)
            if (w == width - 1)
            {
                let br = document.createElement('br');
                document.body.appendChild(br)
            }
        }
    }
}

createBoard(5,10);
.pixel {
    margin:0;
    background-color: rgb(31, 31, 31);
    padding: 10px;
    display:inline-block;
    border: none;
}

.pixel:hover {
    background-color: rgb(73, 73, 73);
}

Answer №1

Here is an updated version of your JavaScript code that creates rows of buttons and adds them to a container. Both the rows and the container have display: flex property applied to them for proper alignment.

function createBoard (height, width)
{
    for (let h = 0; h < height; h++) {
        const row = document.createElement('div');
        row.classList.add('row');

        for (let w = 0; w < width; w++) {
            const button = document.createElement('button');
            button.classList.add('pixel');
            row.append(button);
        }

        document.querySelector('.container').append(row);
    }

}
createBoard(10, 10);
.container {
    display: flex;
    flex-direction: column;
}

.container .row {
    display: flex;
}

.container .row .pixel {
    margin: 0;
    background-color: rgb(31, 31, 31);
    padding: 10px;
    display: inline-block;
    border: none;
}

.container .row .pixel:hover {
    background-color: rgb(73, 73, 73);
}
<div class="container"></div>

Another approach would be to utilize grid, where you need to specify the width of each pixel to create your desired grid layout within the container.

function createBoard (height, width)
{
    document.querySelector('.container').style.gridTemplateColumns = 'repeat('+width+', 20px)';
    for (let h = 0; h < height; h++) {
        for (let w = 0; w < width; w++) {
            const button = document.createElement('button');
            button.classList.add('pixel');
            document.querySelector('.container').append(button);
        }
    }

}
createBoard(10, 10);
.container {
    display: grid;
    flex-direction: column;
}
.container .pixel {
    margin:0;
    background-color: rgb(31, 31, 31);
    display:inline-block;
    border: none;
    width: 20px;
    height: 20px;
}

.container .pixel:hover {
    background-color: rgb(73, 73, 73);
}
<div class="container"></div>

Answer №2

To achieve this task, CSS grid can be utilized:

function initializeGrid(height, width) {
  const grid = document.getElementById('grid');
  while (grid.lastChild) grid.lastChild.remove();
  grid.style.gridTemplateColumns = `repeat(${width}, min-content)`;
  for (let h = 0; h < height; h++) {
    for (let w = 0; w < width; w++) {
      let button = document.createElement('button');
      button.setAttribute('class', 'cell');
      grid.appendChild(button)
    }
  }
}

initializeGrid(16,9);
.cell {
  margin: 0;
  background-color: rgb(31, 31, 31);
  padding: 10px;
  display: inline-block;
  border: none;
}

.cell:hover {
  background-color: rgb(73, 73, 73);
}

#grid {
  display: grid;
}
<div id="grid"></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

Determine if the input value is an integer using a custom validator in Angular 2

Looking for a way to validate integer inputs in an Angular2 project? I experimented with using Number(control.value), but it returns 0 for empty fields, which is not ideal. Another method I tried was parseInt(control.value,10), but it ignores spaces. For ...

The dropdown button becomes unresponsive when attempting to navigate within it using ajax requests

Hello fellow members of the StackOverFlow community, I recently implemented a Bootstrap 5 dropdown button to fetch tabs from the backend using AJAX. Everything was functioning correctly until I encountered an issue where, upon clicking a button within one ...

Display or conceal 5 divs simultaneously

A while back, I stumbled upon this amazing code that has been incredibly helpful. However, I am unable to locate the original author (whoever you are, THANK YOU)... http://jsbin.com/amituh/11/ It's truly awesome, but I would like to add another butt ...

Can you provide guidance on configuring the image class within a DOM element using echo?

What is the method to set the class attribute of an img element using echo function? <div class="allnis" style="padding: 15px; text-transform: uparcase;"> <?php foreach($tv_id->networks as $prod){ echo "<img val ...

Top recommendations for integrating a customized form in Vue

My objective is to develop a unique custom form component named app-form, which offers the capability of using v-model for validation access. The input will be utilizing another custom component called app-input. Here's the progress I've made s ...

Align the image in the center of the page horizontally

Is there a reason why aligning an arbitrary image horizontally is so challenging (or as one response mentioned, "It is not possible.")? I previously had centered images that were functioning correctly for years; however, suddenly they stubbornly position t ...

angularjs identifies the ng-click and href attributes within my event

md-list md-list-item.md-2-line ng-repeat="document in ctrl.documents" div.md-list-item-text ng-click="ctrl.getDocument($event, document)" span ng-bind-html="(document.content | trustedHtml)" Hey there, I've encountered an issue with my md ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

Unable to Style Close Button in React-Bootstrap

As I utilize React-Bootstrap components, I've noticed that all the styling works perfectly fine except for the close buttons embedded within Modals and Alerts. Here are some examples. Expected Alert Component https://i.sstatic.net/0kIo4.png Actual ...

Techniques for linking <span> values to the radar chart's field titles using AngularJS or JQuery

Here is the code snippet containing a list of spans that are generated based on user input: <div id="tags" style="border:none"> <span class="tag" id="4"></span> <input type="text" id="inptags" value="" placeholder="Add max of 6 values ...

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

Use ASP.NET MVC to pass data from an action to an AJAX call and utilize it in the success function

I have a custom ResultOfOperation class that I use to retrieve details about an activity: public class ResultOfOperation { public string Message1 { get; set; } public string Message2 { get; set; } public string Message3 { get; ...

MUI React - Issue with changing SvgIcon color using override

Currently, I am utilizing MUI version 5 within a React project. My objective is to customize the icon color for the Error Alert by using General StylesOverrides. Although I successfully altered the color on the Alert component, I am unable to discover a ...

Stop iframe zooming on Android devices

I am facing an issue with an iframe that contains form elements. I have attempted to include a meta tag within the iframe page: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> Also, I tried se ...

My code includes a function that uses setInterval to generate graphs

Is there a way to stop the setInterval function without causing the graph to disappear? I've noticed that when the setInterval stops, the last 7 points plotted on the graph disappear. How can I prevent this from happening? Any suggestions would be gre ...

Closing the menu on image click in Ionic 2

If you're using Ionic 2, you have the ability to include the menuClose directive on a button to automatically close the side menu when the button is clicked. However, what if you want to close the menu when an image is clicked instead of a button ...

Transmitting information exclusively to a targeted individual rather than broadcasting it to the entire channel

Exploring the features of Faye.js has been my latest project. I am looking to customize the subscription process so that only the specific client receives a unique object upon joining a channel, making it irrelevant to others already present. Any suggesti ...

Are the Class Properties of React or Next.js Internally Managed and Maintained?

Upon reviewing the code snippet provided, it appears that the variable this.mBaseService is initialized before the first debugger, but not after the second debugger. I am curious if anyone can shed light on why this inconsistent behavior occurs. One hypot ...

Change the data returned by Ajax

After making an ajax request, my table gets populated with data from my array. The return is as expected, but now I want to modify this data before displaying it to the user. Whether this modification happens before or after the data is placed in the table ...

How to obtain the current URL of an iframe?

After coming across what seems to be a similar question, I still have to ask for clarification because I couldn't find a clear answer. Allow me to elaborate on my project, I am working on an online store where we offer two types of products, The fi ...