Andy Andy - 2 months ago 7
CSS Question

button is not centered when using jquery append

I wonder why when I am using CSS - my buttons are horizontally centered and when I am using the same code in

append()
the buttons are aligned to one of the sides.

HTML/CSS code:

<div style="width: 100%;text-align: center">
<button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try1</button>
<button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try2</button>
</div>


and the jquery code:

$('#inner_body').append('<div style="margin:auto;display:block;width: 100%;text-align: center">');
$('#inner_body').append('<button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try1</button>');
$('#inner_body').append('<button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try2</button>');
$('#inner_body').append('</div>');

Answer

You can't append div separately with opening and closing tag like that.

Append it all at once like this

$('#inner_body').append('<div style="margin:auto;display:block;width: 100%;text-align: center"><button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try1</button><button id="somebutton" style="margin:20px;padding: 20px;background-color: #718bf3">try2</button></div>');

Or add text-align: center; to #inner_body.

And another solution is to append 'container' div first and then inside it append buttons. Something like this https://jsfiddle.net/mq6446hj/

Also, you can't have same unique identifiers (id) on multiple elements.
You have id="somebutton" for all buttons. Use class instead.