jacouille98
jacouille98

Reputation: 23

I would like to horizontally align buttons and center them with css

I'm trying to align 4 buttons horizontally in the center top of the page with css. this is what I have

button {
  background-color: rgb(243, 243, 243);
  border: 5px;
  color: #000000;
  padding: 15px 32px;
  text-align: center;
  margin: 4px 2px;
  cursor: pointer;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
  display: block;
  margin: auto;
}

whenever i do this, the buttons get align in the center but also vertically, they should be horizantaly. I already tried this:

display: inline-block; instead of display: block;

but then my buttons become aligned horizonatlly but not center on top of my page.

Upvotes: 2

Views: 11141

Answers (3)

edmonan
edmonan

Reputation: 21

There are two options. In both cases, you need to wrap the buttons in a div, nav or some other element. Then, you can use display: inline-block or display: flex to lay them out. The inline-block option is the traditional approach and takes less CSS. If you are interested in your page scaling to all viewport sizes (i.e. responsive design) flex is the better option.

display: inline-block

button {
  background-color: #ccc;
  display: inline-block;
  margin: 5px;
}
nav {
  text-align: center
}
<nav>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</nav>

display: flex

button {
  background-color: #ccc;
  margin: 5px;
}
nav {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
<nav>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</nav>

Upvotes: 2

Miguel Angel
Miguel Angel

Reputation: 983

The best way to do that is with a text alig in the container, like this:

.container {
  text-align: center;
}
 <div class='container'>
      <button>MyBtn1</button>
      <button>MyBtn1</button>
      <button>MyBtn1</button>
 </div>

Upvotes: 2

Sreekanth Reddy Balne
Sreekanth Reddy Balne

Reputation: 3424

Is this what you are trying to achieve??

Place the buttons inside a container and apply text-align:center to it.

.container {
  text-align: center;
}

button {
  background-color: rgb(243, 243, 243);
  border: 5px;
  color: #000000;
  padding: 15px 32px;
  text-align: center;
  margin: 4px 2px;
  cursor: pointer;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
  /*margin: auto;*/
}
<div class='container'>
  <button>MyBtn1</button>
  <button>MyBtn1</button>
  <button>MyBtn1</button>
</div>

Upvotes: 1

Related Questions