简体   繁体   中英

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!

you can use the CSS DOM to achieve it in javascript

you can use the style keyword to style an element

for example if you have this code to center the button in css

<div id="div">
  <button>hi</button
</div>
div{
 display: flex;
 align-items: center;

you can write it in javascript as

const div = document.getELementById("div");
div.style.display = "flex";
div.style.alignItems = "center";

Here are two ways you do to this:

Adding style directly in your javascript:

 // Create button var myCenteredButton = document.createElement('button') myCenteredButton.textContent = 'Here is my centered button' // Before inserting it to the DOM, add your style myCenteredButton.style.display = 'block' myCenteredButton.style.margin = '0 auto' // Insert to DOM document.body.append(myCenteredButton)

Adding a class and letting css style it:

 // Create button var myCenteredButton = document.createElement('button') myCenteredButton.textContent = 'Here is my centered button' // Before inserting it to the DOM, add a class for styling with css myCenteredButton.classList.add('center-me') // Insert to DOM document.body.append(myCenteredButton)
 .center-me { display: block; margin: 0 auto; }

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%)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM