1

I have a container of various width, and various number of boxes float inside it. All the boxes have same width and height.

This is a demonstration. https://jsfiddle.net/kghvmjb6/1/

I am looking for pure CSS solution if possible. Otherwise pure javascript (no jQuery) and CSS solutions are fine.

This example works fine with one line of floating boxes but fail with multiple lines, which is not I want. https://codepen.io/alexandredees/pen/ojaFr

wdetac
  • 2,712
  • 3
  • 20
  • 42

1 Answers1

0

Instead of using float left, use display inline-block and in the parent div add text-align center, that will center the boxes in the container

Modified Fiddle

HTML

<div class="container">
 <div class="">
   <div class="box">1</div>
   <div class="box">2</div>
   <div class="box">3</div>
   <div class="box">4</div>
   <div class="box">5</div>
   <div class="box">6</div>
   <div class="clear"></div>
 </div>
</div>

CSS

.container {
   border: 1px solid red;
   width: 480px; text-align:center;
 }

  .container.wider {
    width: 530px;
  }

 .box {
   float: none;
   width: 80px;
   height: 80px;
   margin: 10px;
   background-color: #ddd;
   display:inline-block;
   }
Sanjeev Kumar
  • 3,113
  • 5
  • 36
  • 77