Centering Child Div In Parent Div

Child Div can be centered in many but here two easiest ways are mentioned-

 Centering an Absolute Element Horizontally

Centering an element horizontally in the viewport or browser window. To get started, let’s bust out a simple div and give it some basic styling.

Parent Div style:
       position:relative;height:300px;width:500px

Child Div style:

position:absolute;left:0px;right:0px; width:100px;height:100px;margin:auto




Centering Absolute Element


An absolutely positioned item contained inside of a relatively positioned item, we need to set the left property.

Option 1:

Parent Div style:
       position:relative;height:300px;width:500px

Child Div style:

position:absolute;left:0px;right:0px;top:0px;  bottom:0px;width:100px;height:100px;margin:auto

Apply this,its centering your child div.

Option 2:

We’ll need another way to center the child that isn’t dependent on the width of the parent. To accomplish this, we need to use a percentage for the left value. The obvious answer is to use 50%, but that won’t really work because you’re not accounting for the width of the element that you’re centering. To make it work, we need to add in a negative left margin of half the width of the child element

Parent Div style:

position:relative;height:300px;width:500px;

Child Div style:

position:absolute;margin-left:50%;margin-top:50%;left:-50px;top:-50px;width:100px;height:100px;

Here noted that for this way child div must be aware about its width and height. Left and top values must be the -(minus) and the half of width and height respectively.




Leave a Reply

Your email address will not be published. Required fields are marked *