-1

I can't seem to center a div horizontally inside another div. Here's my html:

.block {
  padding: 0px 20px;
  max-width: 820px;
  margin: 0 auto;
  background-color: #ff0;
}

.container {
  margin: 0 auto;
  display: inline-block;
  background-color: red;
  padding: 5px;
}
<div class="block">
  <div class="container">
    <button>£10</button>
    <button>£20</button>
    <button>£30</button>
  </div>
</div>

It looks like this:

enter image description here

I want the red div centered inside the yellow div. At the moment it is aligned left.

Here's the codepen: https://codepen.io/carlrippon/pen/MWwaORv?editors=1111

I don't need to support old versions of IE - just IE11

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Carl Rippon
  • 4,553
  • 8
  • 49
  • 64
  • for working `margin: 0 autho;` the div that you set style `margin: 0 auto;` It should not cover the whole space, so must set width for it like `max-width: 80%;` – Ramin eghbalian Feb 12 '20 at 15:28

2 Answers2

0

That worked for me:

.block {
  text-align: center;
  padding: 0px 20px;
  max-width: 820px;
  margin: 0 auto;
  background-color: #ff0;
}
.container {
  margin: 0 auto;
  display: inline-block; 
  background-color: red;
  padding: 5px;
}
<div class="block">
 <div class="container">
   <button>£10</button>
   <button>£20</button>
   <button>£30</button>
  </div>
</div>
0

Your red DIV (.container) is an inline-block, that's why margin: 0 auto won't work.

Just add text-align: center; to its parent (.block)

.block {
  padding: 0px 20px;
  max-width: 820px;
  margin: 0 auto;
  background-color: #ff0;
  text-align: center;
}
.container {
  display: inline-block; 
  background-color: red;
  padding: 5px;
}
<div class="block">
 <div class="container">
   <button>£10</button>
   <button>£20</button>
   <button>£30</button>
  </div>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130