
Tip Details:
- Technology: HTML & CSS
- Difficulty: Beginner
Final Result
Centered Child Div
Basics
For centering any element with css firstly it should be a block level element. Then you must define a width of the element and set its margin to auto. So, generally when your div is not positioned as block level. You code for the centering element should be like this.
.element{ width: 50%; /* can be specified as px, %, or em */ margin: auto;
But when you set the position of the div as absolute you have to specify the position of the parent element. For our purpose we use:
.parent{ position:relative; }
Then after you specify the position of the child element to absolute. it will kinda float to the all left of the parent element. When you set left and right property to 0 then your margin auto will work and set it to center.
.child{ left:0; right:0; margin:auto; width: 70%; }
Final Code
HTML:
The html is simple container with a child element.
<div class="parent"> <div class="child"><span>Centered Child Div</span></div> </div>
CSS:
.parent{ position: relative; /* required */ /* for styling purpose */ border: 2px solid #ddd; background: #bbb; margin: 20px 50px; padding: 30px; } .child{ /* required */ left: 0; right: 0; margin: auto; width: 70%; /* for styling purpose */ border: 1px solid green; padding: 10px; background: #FFF; }