Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  45] [ 2]  / answers: 1 / hits: 5149  / 3 Years ago, sat, june 26, 2021, 12:00:00

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!


More From » html

 Answers
18

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


<!--In only HTML-->
<button style="position: absolute; left: 50%; transform: translateX(-50%);">Click Me</button>

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:


<!--HTML-->
<button id="myButton">Click Me</button>

/*  
CSS
Remember to use a # before the name because it's an id you're trying to reach
*/
#myButton {
position: absolute;
left: 50%;
transform: translateX(-50%);
}

Or you could use JavaScript with the same HTML base


<!--HTML-->
<button id="myButton">Click Me</button>

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


// Javascript
let myButton = document.querySelector("#myButton"); myButton.style.position = "absolute";
myButton.style.left = "50%";
myButton.style.transform = "translateX(-50%)";

[#1179] Saturday, June 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briannar

Total Points: 354
Total Questions: 103
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
briannar questions
Tue, Aug 31, 21, 00:00, 3 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 7, 20, 00:00, 4 Years ago
Sun, Feb 23, 20, 00:00, 4 Years ago
;