1

I have array of object with rule

{width:10%, float:left,display:block;height:20px}

If I have 10 objects, it will be displayed in one line,one by one, so its fine. My problem is, if i print less than 4 objects ,I want to display them on center of page, without floating left .... In another case , if I have e.g 33 objects, I want to display 3 full rows with left floating objects, 10 in one row ... and last row with 3 objects must be aligned on center page. Any suggestion how to solve this with css?

Thanks

Ilya Yaremchuk
  • 2,007
  • 2
  • 19
  • 36
Sovabass
  • 21
  • 1
  • Possible duplicate of [How to center multiple divs inside a container in CSS](https://stackoverflow.com/questions/17188455/how-to-center-multiple-divs-inside-a-container-in-css) – George Feb 08 '18 at 00:34

3 Answers3

0

I think I get the idea of what your trying to do and this can be achieved nicely with flex. Take a look at this demo

.container {
  border: 1px red solid;
  width:408px;
  display:flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  border: 1px solid blue;
  width:100px;
  height: 100px;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>

</div>
Niles Tanner
  • 3,911
  • 2
  • 17
  • 29
0

Create a wrapper on your DIV and center text

.wrapper {
  text-align: center;
}

Then use inline-block to your DIV's items to achieve the desired...

.wrapper div {
  width:10%;
  display:inline-block;
  height:20px;
  background: #ff0000;
  border: 1px solid #fff;
  }

.wrapper {
  text-align: center;
}
.wrapper div {
  width:10%;
  display:inline-block;
  height:20px;
  background: #ff0000;
  border: 1px solid #fff;
  }
<h1>4 divs</h1>
<div class="wrapper">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<h1>33 divs</h1>
<div class="wrapper">
 <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
 </div>
caiovisk
  • 3,667
  • 1
  • 12
  • 18
0

You can achieve this by using flex. Use

 flex-wrap:wrap

to make sure your items wraps whenever it overflows horizontally, then use

justify-content:center

to center them horizontally. Plunk here.

Good to know: if you were to encounter aligning/centering vertically, you can use align-items: center following this approach.

Hope this helps!

grey.dim
  • 156
  • 6