Saturday, August 10, 2013

CSS - Center alignment revealed ;)

Ever wondered how to center align elements using CSS?? :)
1) Horizontal center alignment:

HTML:
<div id='a'>
    <div class='h-center'>
          horizontal center
    </div>
</div>

CSS:
.h-center{
  background: red;
  margin: 0 auto;
  width:100px;
  height:100px;
}
#a {
    background: green;
    width: 200px;
    height:200px;
    position:relative;
}
OUTPUT:
















2) Horizontal & Vertical center alignment:

HTML:
-----------------------

<div id='a'>
    <div class='abs-center'>
      absolute center
    </div>
</div>



CSS:
-------------------------
.abs-center {
  background: red;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
}
#a {
     background: green;
    width: 200px;
    height:200px;
    position:relative;
}

OUTPUT:
-------------------------------
















Further reading.
http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

No comments:

Post a Comment