Aligning buttons using JavaScript

I'm currently working on a layout with a horizontal div where buttons (referred to as letters in the code) are being created. However, I've encountered an issue where the buttons are aligning to the left side of the div and I'm unable to center them. Despite applying text-align:center in the CSS for the #letter label, the buttons still refuse to center.

If necessary, here is the section of code responsible for generating the buttons:

// Generates letters for the selected word.
function letterMaker() {
    for (i=0; i<word.length; i++) {
        var letter = document.createElement("input");
        var letters=(shuffledWord).split("");
        letter.type = "submit";
        letter.value = letters[i];
        letter.id = "letter" + i;
        letter.onclick = letterClick.bind(this, letter.value);
        letter.setAttribute('id', 'letter');
        document.getElementById("letterbar").appendChild(letter);
    }
}

Here is the section of code where the button attributes are defined:

#letter {float:left;height:60px;width:60px;background-color:#C0C0C0;border-color:#000000;border-style:solid;border-width:1px;border-radius:5px;font-size:25px;font-family:century gothic}

Answer №1

Make sure to position the buttons within a <section> that has the CSS property margin: auto;, all contained within the parent element div#letterbar.

Answer №2

It seems like you might be applying the alignment to each individual element instead of the container.

You can try this:

#letterbar { text-align: center;}

According to MDN specifications, text-align does not control the alignment of block elements itself, only their inline content.

Another point worth mentioning is that using 'class' instead of 'id' is recommended due to the fact that HTML5 specifications state that an id must be unique in a document, and it appears your loop generates multiple inputs with the same id.

You can view an example on JSFiddle here: http:// jsfiddle.net/UuxuX/

Edit

Adding on to my previous comment, if you apply a float to the inputs on the left, the text-align property will have no effect. If you simply want to center the inputs within a div, remove the float from the input and align the text inside the div instead.

Answer №3

To center the element, apply the auto value to the margin using CSS:

#letter {margin:auto;...}

Answer №4

I concur with JanParowka and his previous statement.

If the identifier of the div is "letterbox," then you should implement the following:

#letterbox { text-align: center;}

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

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

Using jQuery to alter the background color when a div reaches a specific height

Is there a way to make my sidebar change color gradually as the user scrolls below a certain point on the page? I want the background to transition from transparent to black, giving it a fading effect. I attempted to modify some existing code without succe ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

"Make sure the last if statement is always the one being executed

I have been using angularjs to develop a mini quiz application. I created 4 if statements, but for some reason, the last condition is always executed even if no answers have been selected. Why does $scope.makeup consistently display You should have makeup ...

Tips for managing the ever-evolving language state in expressJS

I am currently working on a project utilizing nodeJs, handlebars, and the expressJs framework. I have implemented a language change functionality using the i18n-express module. This module adds a query string at the end of the URL when changing languages. ...

Retrieve the value of a dropdown menu that contains multiple selections associated with a single model

My current code generates a calendar entry listing for the courtroom, with each case having a "status" dropdown that is set by the judge post-hearing. I now need to save this data in the database. I have successfully added ng-change which triggers the desi ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

Every time I click a button, I am trying to add JSON objects into an array and then show the outcomes

Currently, my goal is to create a random selection feature from an array that users can contribute to by clicking a button. I am a bit unsure about how to proceed with this task. The application is developed in React and it utilizes the movieDB's API ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

Challenges with Access-Control-Allow-Origin within the website's domain

Why am I encountering an issue when attempting to make an XMLHTTPRequest from a JavaScript file to a web service on the same domain, resulting in: Access-Control-Allow-Origin error stating that the origin is not allowed? Switching mydomain.com to localh ...

Error: Angular encountered an unexpected token in the syntax

I am encountering an issue while trying to incorporate a user's profile updater on my website. Whenever I attempt to access a user's profile on the site, I run into this Angular error: main.ts:6 ERROR SyntaxError: Unexpected token 'e', ...

Executing callback function within Observable.prototype.subscribe in Angular 2

Having issues with the complete callback not functioning as intended. Here's a breakdown: Take a look at this image and note the complete callback within the subscribe method. The complete function is only triggered when observerOrNext is called. If ...

The concept of selective importing within JavaScript

Seeking guidance on configuring conditional imports for a native library that is built for both node and electron. The challenge arises when one project requires the node implementation for testing, while another project needs the electron version. Projec ...

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

I am in possession of 10,000 entities in cesium. What is the best way to avoid using a loop to modify their material?

Starting new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.15, color: Cesium.Color.fromCssColorString("rgba(42,92,170, 0.15)") }); Ending new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.3, ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...

What is the method to retrieve the index of a matching element from a JSON object?

var radioRenderData = [{ "type": "radio-group", "label": "Radio Group", "className": "radio-group", "name": "radio-group-1479370460494", "values": [{ "label": "Option A", "value": "option-a", "selected": false }, { "label": "Opt ...

What is the best way to assign multiple events and handlers using the .on method?

I've been attempting to move a submenu using multiple handlers within the on method. My goal is to trigger the function panelON when the mouse enters one of the li elements, and execute the function panelOFF when the mouse leaves it. I have tried dif ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...