Search code examples
htmlcssmargintailwind-css

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


I am trying to center horizontally a button. This button is in a container which already centers itself using margin-left:auto and margin-right:auto.

unfortunately I cannot do the same for the button inside this container which would have been easier because I could have used one class for the container and the button.

I am using Tailwind classes for my project and the mx-auto class which is margin-left:auto AND margin-right:auto works for the container but not the button hence this question. Why can I not use that class for my button ?

.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>


Solution

  • Because the button has display: inline-block, it's not about how tailwind works. you can change the button's display to block or add block to its class (tailwind). for more info about this checkout this answer

    Alternatively, you can set the parent's display to flex and center button vertically and horizontally by justify-content: center and align-items: center