为什么我不能使用 mx-auto 将子元素水平居中?

Why can I not center horizontally a child element using mx-auto?

我正在尝试将按钮水平居中。此按钮位于已使用 margin-left:auto and margin-right:auto.

居中的容器中

不幸的是,我不能对这个容器内的按钮做同样的事情,这本来会更容易,因为我可以为容器和按钮使用一个 class。

我正在为我的项目使用 Tailwind classes,而 mx-auto class 即 margin-left:auto AND margin-right:auto 适用于容器,但不适用于按钮,因此出现了这个问题。为什么我不能将 class 用于我的按钮?

.container {
  max-width: 550px;
  margin-left: auto;
  margin-right: auto;
  background-color: yellow;
  height: 92px;
}

.btn {
  margin-left: auto;
  margin-right: auto;
 /* display: table;
  margin: 0 auto;*/
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="output.css">
    <title>This is the title of the webpage!</title>
  </head>
  <body>
      <div class="container">      
            <button class="btn">boutton</button>        
      </div>
  </body>
</html>

如果您试图将按钮对齐到容器的中心,则必须先告诉元素如何显示,然后才能依赖 margin-left: auto; or margin-right: auto;`。对于实现居中按钮的这个特定应用程序,我将执行以下操作:

.container {
  max-width: 550px;
  margin-left: auto;
  margin-right: auto;
  background-color: yellow;
  height: 92px;
}

.btn {
  margin-left: auto;
  margin-right: auto;
  display: flex;  /*Using CSS to give the container the ability to alter its items' width/height // Hence - margin: auto now works properly.*/
/*display: table; Using a display: table; would really only apply if you were using a table structure in your HTML*/
  margin: 0 auto;  
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="output.css">
    <title>This is the title of the webpage!</title>
  </head>
  <body>
      <div class="container">      
            <button class="btn">boutton</button>        
      </div>
  </body>
</html>

mx-auto class 用于水平居中的固定宽度块级内容,即具有 display: block 和宽度设置的内容——通过将水平边距设置为自动。 你可以使用 flex-box 来居中高度。 最后你可以从 .btn class

中省略 margin-left: auto; margin-right: auto;
.container {
  max-width: 550px;
  display: flex;
  justify-content: center;
  background-color: yellow;
  height: 92px;
}

因为按钮有 display: inline-block,这与 tailwind 的工作原理无关。 您可以将按钮的显示更改为 block 或将 block 添加到其 class(顺风)。 有关此结帐的更多信息 this answer

或者,您可以通过 justify-content: centeralign-items: center

将父项的显示设置为 flex 并将按钮垂直和水平居中