Search code examples
htmlcssflexboxcenteringtext-alignment

Why can't I use flex with <button> elements?


I have the following code in index.html

h1 {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
}

#count-el {
  font-size: 50px;
  display: flex;
  justify-content: center;
}

#increment-btn {
  background: red;
  color: white;
  font-size: 40px;
  display: flex;
  justify-content: center;
}
<h1>People entered:</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn">Increment</button>

Flex works in all elements except for the <button> element. It doesn't center it. Why is that?


Solution

  • add to your button class margin-left: auto; margin-right:auto;
    should look like that

    #increment-btn {
      background: red;
      color: white;
      font-size: 40px;
      display: flex;
      justify-content: center;
      margin-left: auto;
      margin-right: auto;
    }