14

I have 2 divs, parent and child, I want that child left side (left border) will in center of parent.

Why this code not working? that is left: 50% for child, is not working.

<div id="outher">
    <div id="inner">

    </div>
</div>

css:

#outher {
   width: 1000px;
   height: 1000px;
   background-color: #ccc;
}

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   left: 50%;
}

demo http://jsfiddle.net/vrse2/5/

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

5 Answers5

33

You need to set position to absolute or relative:

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
11

CSS left only works with positioned elements.

Quoted from W3C

Values  <length> | <percentage> | auto | inherit
Initial value   auto
Applies to  positioned elements
Inherited   No

Try

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}

Good read

  1. MDN : CSS Reference -left (Best IMHO)
  2. W3C : CSS/Properties/left
Maxwell175
  • 1,954
  • 1
  • 17
  • 27
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
6

You need to add position: absolute; to your CSS. left is used for absolute positioning.

In your case:

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}
Maxwell175
  • 1,954
  • 1
  • 17
  • 27
Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
3

Use:

margin-left: 50%;

Or:

position:relative;
left:50%;
Tom Walters
  • 15,366
  • 7
  • 57
  • 74
  • `margin-left` is something totally different. For more info on this, see http://stackoverflow.com/questions/6419411/top-left-vs-margin-top-margin-left. – Maxwell175 Mar 01 '14 at 04:12
2

Try With the following :

HTML Part :

<div id="outher">
    <div id="inner">

    </div>
</div>

CSS Part :

#outher {
    width: 1000px;
    height: 1000px;
    background-color: #ccc;
}

#inner {
    width: 400px;
    height: 300px;
    background-color: #090;
    left: 50%;  
    margin:0 auto;
    position: absolute;
}

I think this may help you to resolve your problem.

John Peter
  • 2,870
  • 3
  • 27
  • 46