nachime nachime - 4 months ago 41
CSS Question

bootstrap dynamically centering columns

I have a horizontal bar and I want to put sections into that bar. I can't think of a way to center them dynamically -- ie if I have 1 section its put to the center, if I have 2 sections they're put straddling the center, if I have 3 sections the middle section is centered and the other two are on either side, etc. I'm changing the number of sections with javascript so I can't just solve this for a particular number of sections.

How should I do so? Also I realized that the section names aren't showing up on the snippet (but they are on my actual site).



.middle-section {
height: 100px;

width: 800px;
margin: 0 auto;
background-color: #F6F7F8;
border-radius: 5px;
transform: translate(0%,-50%);

-webkit-box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);
-moz-box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);
box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class = 'container-fluid'>
<div class = 'middle-section'>
<div class = 'row'>
<div class ='col-md-2'>
Section
</div>
<div class ='col-md-2'>

Section
</div>

</div>

</div>
</div>




Answer

I used flexbox to solve your problem, just add some divs to try it :

JSfiddle

You can chose to justify all your divs : center, space-around or space-beween

.middle-section {
  height: 100px;
  
  width: 800px;
  margin: 0 auto;
  background-color: #F6F7F8;
  border-radius: 5px;
  
  -webkit-box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);
-moz-box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);
box-shadow: 2px 2px 5px -2px rgba(0,0,0,0.75);
  
}

.row {display:flex; flex-wrap:wrap;justify-content:space-around; }

.row-child {border:1px solid black;}
<div class = 'container-fluid'>
  <div class = 'middle-section'>
    <div class = 'row'>
       <div class ='col-md-2 row-child'>
         Section 
       </div>
       <div class ='col-md-2 row-child'>
   
         Section
       </div>
      
      </div>
    
    </div>
  </div>