Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS align elements starting from center

I'm trying to align elements in a bootstrap col starting from the center all the way to top and bottom. example:

  • When there is one element:

        <div class="col-md-3">
    
    
         <span> item #1 </span>
    
    
         </div>
    

Element one is centered on the middle with empty margins above and below. When pushing more items:

  • When there are two elements

         <div class="col-md-3">
    
    
          <span> item #1 </span>
          <span> item #2 </span>
    
    
         </div>
    
  • When there are three elements

         <div class="col-md-3">
    
          <span> item #1 </span>
          <span> item #2 </span>
          <span> item #3 </span>
    
         </div>
    
  • When there are four elements

          <div class="col-md-3">
    
          <span> item #1 </span>
          <span> item #2 </span>
          <span> item #3 </span>
          <span> item #4 </span>
    
         </div>
    

Not so accurate but something like this - Demo : http://jsfiddle.net/23ktww1o/1/

like image 794
EnderCode Avatar asked Mar 06 '26 03:03

EnderCode


1 Answers

  1. Make your spans display: block;
  2. Wrap your spans in a div with display: table-cell and vertical-align: middle

Example:

div.col-xs-3 { height: 240px; display: table}
div.cell  { 
  display: table-cell; 
  vertical-align: middle; 
  height: 100%;
  border: 1px solid gray; 
}
span { display: block; }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-xs-3"> 
      <div class="cell">
         <span> item #1 </span>
         <span> item #2 </span>
      </div>
    </div>
    <div class="col-xs-9"> 
         <span> item #1 </span>
         <span> item #2 </span>
         <span> item #2 </span>
         <span> item #2 </span>
    </div>  
</div>

Edit: (based on op's comment)

In order to make the div take up the height of the parent, make it 100% and also display: table to the parent. You can also have the height on the row div and set 100% on the inner col.

like image 156
Abhitalks Avatar answered Mar 07 '26 17:03

Abhitalks