-1

I am trying to create a row of three buttons in Javascript using dynamically set CSS Style, but I am having difficulty trying to center the row of buttons in the middle of the page. This is with buttons that are currently not part of a div.

I have tried button.align = 'center'; with no success.

Here is the link to jsfiddle snippet.

HTML SKELETON

  <head>
    <meta charset="utf-8">
    <title>Buttons</title>
  </head>

  <body>

    <script>
    </script>

  </body>

</html>

JAVASCRIPT

var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  // put the buttons on page
  document.body.appendChild(one);
  document.body.appendChild(two);
  document.body.appendChild(three);

}

buttonTest();
termlim
  • 865
  • 1
  • 6
  • 13
  • Possible duplicate of [How do you easily horizontally center a
    using CSS?](https://stackoverflow.com/questions/618097/how-do-you-easily-horizontally-center-a-div-using-css)
    – André Dion Feb 06 '18 at 18:17
  • 2
    You need to wrap the buttons in a container. Use `text-align: center` in the container and you're done. – Ricky Ruiz Feb 06 '18 at 18:17
  • Andre Dion, I have looked at that post before, but it wasn't clear how to do this via dynamically set CSS Styling. – termlim Feb 06 '18 at 18:25

2 Answers2

1

Link Here

var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  var divElem = document.createElement('div');
  divElem.setAttribute('style', 'text-align:center;');
  // put the buttons on page
  //document.body.appendChild(one);
  //document.body.appendChild(two);
  //document.body.appendChild(three);
  divElem.appendChild(one);
  divElem.appendChild(two);
  divElem.appendChild(three);
    document.body.appendChild(divElem);
}

buttonTest();
Rick Riggs
  • 336
  • 2
  • 12
0

A quick solution would be adding text-align : center to the body

var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  // put the buttons on page
  document.body.appendChild(one);
  document.body.appendChild(two);
  document.body.appendChild(three);

}

buttonTest();
body {text-align: center;}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Buttons</title>
</head>

<body>

  <script>
  </script>

</body>

</html>
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35