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?
Asked
Active
Viewed 1,559 times
0
Praveen Kumar Purushothaman
- 160,666
- 24
- 190
- 242
ScubaSteve
- 6,836
- 7
- 49
- 56
-
1You can call the centering function on window.resize – Pete Feb 14 '13 at 14:17
-
2what 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 Answers
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
- 146
- 2
- 15
-
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
-
1http://jsfiddle.net/GkGBT/ Works with display:inline-block. Am I missing a part of the question? – Matt Rogers Feb 14 '13 at 14:29
-
-
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
-
1Thank 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