0

I have a floating left div so that it wraps the content. I would like to center this div. Unfortunately, since I do not know the exact width of this div, I cannot use margin: 0 auto;. So, I decided to use jQuery to center the div. I was able to do this correctly by using .outerWidth(). The issue is, I would like the div to remain centered when the page grows/shrinks. I thought setting the margin-left to a percentage would accomplish this, but it does not. Is there a way to do this?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
ScubaSteve
  • 7,724
  • 8
  • 52
  • 65
  • 1
    You can call the centering function on window.resize – Pete Feb 14 '13 at 14:17
  • 2
    what about http://stackoverflow.com/questions/641857/javascript-window-resize-event. This way you can create a function to calculate the placement. Just Call your function with the initial opening and the way which is described in the linked thread. – sascha Feb 14 '13 at 14:21
  • Post some code that you have tried and also the html markup.. – palaѕн Feb 14 '13 at 14:25

1 Answers1

3

You don't need the exact width of a div to center it. You can see it working here jsfiddle.net/GkGBT

CSS

body{
    text-align:center;
 }
.centerdiv{
   background:blue;  
   display:inline-block;
   margin-left:auto;margin-right:auto;
   text-align:left;
 }

HTML

<div class="centerdiv"></div>
Matt Rogers
  • 156
  • 2
  • 16
  • 2
    *"Unfortunately, since I do not know the exact width of this div, I cannot use margin: 0 auto;"* and with no width set it won't work – Zoltan Toth Feb 14 '13 at 14:24
  • 1
    http://jsfiddle.net/GkGBT/ Works with display:inline-block. Am I missing a part of the question? – Matt Rogers Feb 14 '13 at 14:29
  • changed the -1 to +1 nice hack :) – fmsf Feb 14 '13 at 14:33
  • It's not the `.centerdiv` but the `body` text-align who does the job here. Not sure if that's suitable for OP, but the solution works, so removed the -1 :) – Zoltan Toth Feb 14 '13 at 14:36
  • 1
    Thank you. It wasn't working for me for a while, but that was because float: left (which I was using to force the div to wrap the content) was preventing it from working. I did not realize that display: inline-block also wraps. – ScubaSteve Feb 14 '13 at 14:47