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

Viewed 42

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?

4 Answers

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

Most browsers display button elements as inline-block by default, so, it won't occupy 100% of parent's width. If you apply width 100% it will center the text, just like h1, h2. If you want to center the button itself you can use margin: 0 auto; property.

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

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

#increment-btn {
  width: 100%;
  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>

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;
  margin-inline: auto;
}
<h1>People entered:</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn">Increment</button>

Add margin-inline: auto to your button styles.

Related