This is a followup to my question here. I would like to understand why applying position:absolute to the CSS of a div via jQuery fails, while applying it in a static style works. Here are two jsfiddle examples:
Works: http://jsfiddle.net/jasper/Ty6Af/2/
No worky: http://jsfiddle.net/Ty6Af/3/
Note that the only difference between the two is where I apply position:absolute. Vertical centering always works, but horizontal centering does not work when the page loads for the first time. If you manually re-size the window the div will center correctly.
All of my testing has been on Chrome under Ubuntu thus far.
Anyway, I’m just now delving into the world of web development and these are exactly the kinds of ‘quirks’ that I need to begin understanding.
EDIT:
@Jasper found something interesting. If you make two calls to .css(), first applying position and subsequently applying a margin, it works. I would love to understand why. Here is an example: http://jsfiddle.net/jasper/Ty6Af/5/
So the issue is with how the width of the div is calculated by the browser depending on its
position.position : static(by default) then it’s width is 100% of it’s parents width and the element is not allowed to move around the page.position : relativethen it’s width is 100% of it’s parents width but it can be moved around withleft.position : absolutethen its width is determined by the actual content of the div, for instance if there is only a200pxwide<span>element within the div then the div will be200pxwide.You can test these observations by changing the CSS of your jsfiddle to specify
position : relative(etc…) and remove the JavaScript that makes the divposition : absolute, then use your Developer Tools to inspect the element and it’s calculated width.The problem with your code is that it sets the
position : absoluteat the same time it sets themarginof the element by using its width/height (which are calculated differently depending on thepositionof the element).If you want to set the
positionof the div in JavaScript then you can do something like this:Here’s a jsfiddle: http://jsfiddle.net/jasper/Ty6Af/8/