Skip to content
Advertisement

How to center a button in Javascript

I am trying to center a button in Javascript so that it is horizontally centered in the page. Right now, my button is in a in my html file, so I don’t know how I can use CSS to center it since it’s in Javascript.

TLDR: In Javascript, if I hvae declared a button btn, what code should I write to center it horizontally?

I have searched all over the internet for a way to use Javascript to center a button to no avail. I hope you all can help me.

Thank you!

Advertisement

Answer

If I understand you correctly you want to center an already created button, it could work something like this:

JavaScript

Another way to do it is to set an id to the button and then center it in a separate CSS file or in the <style> tag like so:

JavaScript
JavaScript

Or you could use JavaScript with the same HTML base

JavaScript

And then in a separate JavaScript file or in the <script> tag

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement