如何在 Javascript 中使按钮居中

How to center a button in Javascript

我试图将 Javascript 中的按钮居中,以便它在页面中水平居中。现在,我的按钮在我的 html 文件中,所以我不知道如何使用 CSS 将它居中,因为它在 Javascript.

TLDR:在 Javascript 中,如果我声明了一个按钮 btn,我应该编写什么代码使其水平居中?

我在整个互联网上搜索了一种使用 Javascript 使按钮居中的方法,但无济于事。希望大家帮帮我。

谢谢!

您可以使用 CSS DOM 在 javascript

中实现它

您可以使用 style 关键字来设置元素的样式

例如,如果您使用此代码将按钮居中 css

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

你可以在javascript中写成

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

您可以通过以下两种方式执行此操作:

直接在您的 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)

添加 class 并设置 css 样式:

// 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;
}

如果我对你的理解是正确的,你想将一个已经创建的按钮居中,它可以像这样工作:

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

另一种方法是为按钮设置一个 id,然后将其置于单独的 CSS 文件或