0

Please have a look at the example below, than contains a large div which in turn contains a lot of smaller divs inside.
Each div has a fixed width of 150px and a display of inline-block, so the browser will fit as many as possible in a single line.
The problem is that whenever there is unoccupied horizontal space in the large div it doesn't get shared by the margin: auto property of the children, but rather stays on the left of the large div.

#parent {
  border: 1px solid red;
  display: block;
  width: 100%;
}

#parent>div {
  border: 1px solid black;
  text-align: center;
  width: 150px;
  display: inline-block;
  margin: 0 auto;
}
<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
  <div>13</div>
  <div>14</div>
</div>

Is there a way to center the divs while also allowing more than one div per row and having the same alignment on the bottom regardless of how many elements it shows?

nick zoum
  • 7,216
  • 7
  • 36
  • 80

3 Answers3

0

Remember that display: inline-block basically displays a block element as if it were a word. So if I understood your problem correctly, it should be enough to add this CSS

#parent {
  text-align: center;
}
elveti
  • 2,316
  • 4
  • 20
  • 27
  • This does answer my question, but this messes the margin of the bottom row (I understand that I didn't specify that on the question, and that it's my fault). Is there a way to make it so that the divs on the bottom row are properly aligned? – nick zoum Dec 17 '19 at 16:08
  • @nickzoum Please define "properly aligned" – j08691 Dec 17 '19 at 16:14
  • @nickzoum it's a bit more complicated then. There is `text-align-last: left` but that just pushes the whole line to the left, don't think that's what you want. Are you able to modify the HTML? Or should it be CSS only? – elveti Dec 17 '19 at 16:14
  • @elveti Even if i can modify the html (fairly easy in my case), I would need a different amount of elements depending on the current width of the page. – nick zoum Dec 17 '19 at 16:17
  • I'm accepting and upvoting, not sure why you got the downvote. – nick zoum Dec 18 '19 at 15:28
0

You should add text-align:center to your parent

#parent {
  border: 1px solid red;
  display: block;
  text-align:center;
  width: 100%;
}

hope that was your question.

Ekin Alcar
  • 125
  • 3
  • 7
0

#parent {
  border: 1px solid red;
  display: block;
  width: 100%;
  text-align: center;
}

#parent>div {
  border: 1px solid black;
  text-align: center;
  width: 150px;
  display: inline-block;
  margin: 0 auto;
}
<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
  <div>13</div>
  <div>14</div>
</div>

Set the parent text-align to center.

Siddharth Pal
  • 1,408
  • 11
  • 23