Categories
CSS-Tutorial

Vertical centering using CSS- when child DIV placed in a ‘container DIV of fixed height’

How to vertically center a CHILD DIV inside a CONTAINER DIV of FIXED height. Child DIV height can be in Pixel or percentage of container DIV’s height.

Vertically center a DIV inside a container DIV element. The container can be relatively positioned. The child DIV should be absolutely positioned and its top, right, bottom, and left offset properties specify the element’s position w.r.t the container block (what the element is positioned relative to) and this value should be 0. So now use these properties to vertically center a DIV inside a container DIV element.

How to vertically center a CHILD DIV inside a CONTAINER DIV of FIXED height. Child DIV height can be in Pixel or percentage of container DIV’s height.

  • The CONTAINER DIV has declared height in PX/Pixel or EM.
  • You can declare the height of CHILD DIV using % or pixels.
  • If you don’t mention CHILD DIV width/height it will take whole width/height of Container.

Container DIV height must be declared. Also you need to specify the height of child DIV

<style type="text/css">
.container {
          background: #03F;
          position:relative;
          height:400px;
}
.child1 {
          position: absolute;
          top:0; left:0;
right:0;
bottom:0;

          background:#3CF;
          margin:auto;
          width:40%;
          height:60%;

}
</style>

<div class="container">container DIV
          <div class="child1">
                    Child DIV. <em><strong>Margin : auto</strong></em> of child div centers it w.r.t container DIV.

          </div>
</div>

 

container DIV

Child DIV. Margin : 0 auto of child div centers it w.r.t container DIV.

I have found a good tutorial on vertical centering of div element content.

View Live Examples of Vertical Centering

Also you will find here some examples of vertical centering within view-port or with in a container div :

  • http://cahnory.fr/css/xy-align.html
  • http://www.flashjunior.ch/school/test/divcentering/

Reference Reading :