-1

I have two divs, one inside another. The width of the outer div is given in percentage and the inside div is given an position:absolute. I want to align the inner div in the center of outer div irrespective of the outer div's width percentage.

It works fine when position:absolute is removed from the inner div, but I need that. Any help would be greatly appreciated.

I have the following code:

<div class='container' style='width:70%; position:relative'>
   <div style='position:absolute; text-align:center' align='center'>
        //contents
   </div>
</div>
Anita Sharma
  • 175
  • 4
  • 13
  • check out this question, for example - http://stackoverflow.com/questions/11332414/simplest-vertical-alignment-we-can-think-of – shabunc Jul 25 '12 at 11:22
  • possible duplicate of [How to center DIV in DIV?](http://stackoverflow.com/questions/114543/how-to-center-div-in-div); That question was asked a trillion times out on the web… – feeela Jul 25 '12 at 11:24

1 Answers1

2

You can do the following:

  1. Add text-align:center to the .container div:

    .container{
        text-align:center;
    }
    
  2. If you're trying to center another div or an image etc within .container then set those items to have the following margin:0 auto;, e.g.

    .container > div{
        margin: 0 auto;
        /* note that div needs to be a block element and needs a given width */
    }
    

That should help with your problem.

Zeta
  • 103,620
  • 13
  • 194
  • 236
Billy Moat
  • 20,792
  • 7
  • 45
  • 37
  • didnt help. I tried doin margin:0 auto too. It also didnt work – Anita Sharma Jul 25 '12 at 11:38
  • @anaida - can you give us a link to your page or create a jsfiddle using your code? – Billy Moat Jul 25 '12 at 11:40
  • Here I want the footer div to align in the center of `75% div`. It works fine when i do `text-align:center` or `margin:0 auto`. But it also needs to be at the bottom of the page. So when I give `position:absolute` to footer div it does not align in the center anymore and shifts towards left. Code Here: http://jsfiddle.net/anaida/C9e6a/1/ – Anita Sharma Jul 25 '12 at 11:52
  • Ah. You never mentioned the position:absolute bit above. It's that which is causing your footer to not center. To get it to align to center give your footer a "left" value of "50%" then give it a negative margin-left of half the width of the footer element. – Billy Moat Jul 25 '12 at 11:54