I generate a div for my javascript automated validation script. It is generated with below code:
var alertbox = document.createElement("div");
Now how do i center that div programatically both horizontally and vertically?
Note: Currently I am showing an alert box but once i know how to center a div, i will
replace the alertbox with this dynamically generated div which will also provide some
lightbox-like effect.
Thanks
Note: For reference, you can download latest version of this script here.
Please note that i dont want to use external css for this because this is validation script and it should be able to do it programatically. For example:
using something like this can be helpful:
alertbox.style.position: whatever
....
It’s a matter of applying the same CSS rules as you would have with static content. Horizontal centering can be achieved as described in this article – basically you give the div a fixed with and set left and right margins to
auto. Vertical centering is a bit trickier – a few approaches are discussed here and detailed in this this blog post.The tidiest way is probably to define a CSS class that takes care of the centering and then apply that class to the dynamically generated element like this:
Update:
Since you are already using JavaScript for creating the div, you could of course use it for the centering as well (in combination with CSS absolute positioning) – that would actually probably be a cleaner solution (due to the hackishness of the CSS vertical centering). Exactly how you do this depends a bit on what tools you are using – it’s probably much easier to achieve with a JS framework such as Prototype or jQuery than with “raw” JavaScript since browsers handle window/browser heights a bit differently.