-1

I was centering the elements of my page with:

display: block;
margin-left: auto;
margin-right: auto;

but when I try to do this with one div that has two buttons they stay in the left corner, why? and how I place them in the center.

sunnyu
  • 1
  • 1

4 Answers4

0

Option 1 If both the buttons are inside the div container you also need to specify the width of the div container, because by default div covers the complete width.

div{
  max-width:10rem;
  margin :0px auto;
}
<div>
  <button>Button1</button>
  <button>Button2</button>
</div>

Option 2 You can also flex the div container to center the buttons

div{
  display:flex;
  align-items:center;
  justify-content:center;
  }
<div>
  <button>Button1</button>
  <button>Button2</button>
</div>

Option 3 You can also use the simple text align center property on the div container so it will center the buttons

div{
  text-align:center;
}
<div>
  <button>Button1</button>
  <button>Button2</button>
</div>

because buttons are inline elements.

Vinay Khatri
  • 312
  • 1
  • 8
-1

The div css:

text-align: center
James Risner
  • 5,451
  • 11
  • 25
  • 47
Mahmoud Hassan
  • 328
  • 1
  • 8
-1

Not sure about the context but you can use this centering pattern (both horizontal and vertical) with Flexbox as well:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
Sigma
  • 234
  • 2
  • 6
-1

Positioning is very easy with flexbox. Please try following properties on your div

display: flex;
justify-content: center;
align-items: center;

Justify content will place content centrally along horizontal axis and align items will place content centrally along vertical axis (for flex direction row which is default)