We recently ran into a situation where we were dynamically showing and centering model popup windows in an ajaxified environment. Our initial implementation had one down side.
We were showing and dynamically centering our div/panels via JavaScript. The windows would very briefly show up in its default location before jumping to center. Not a huge problem, but very annoying.
Our initial approach looked something like this. Statically build a hidden div/panel and when the user triggers a pop up dialog, call the CenterPanel method from JavaScript and show the panel. We were calculating the screen height and width and making it available globally.
The JavaScript process looked something like this...
CenterPanel("<%= SendToGeneralQueuePopupPanel.ClientID %>");
function CenterPanel(panelId){
var panel = document.getElementById(panelId);
if (panel) {
panel.style.top = ((screenHeight / 2) - (GetSize(panel.style.height) / 2)) + 'px';
panel.style.left = ((screenWidth /2) - (GetSize(panel.style.width) / 2)) + 'px';
}
}
The result was a panel that would show up, then jump to the center of the screen. (Annoying)
After getting a bit of time to think about the issue, I remembered a much simpler way to center a control with pure CSS rather than dealing with problematic JavaScript at all. I'd used this technique in other projects and it makes things quite a bit more simple and stops the panel from jumping around the screen.
The CSS method...
We define a Panel to use as the pop that applies our modalPopup CssClass. Notice that the panel's Width is 200 and it's Height is 60.
<asp:Panel ID="PanelPopup" runat="server" CssClass="modalPopup" Width="200" Height="60">
<div style="text-align:center;">
Are you sure you wish to continue?</div>
<div style="text-align:center;">
<asp:Button ID="ButtonYes" runat="server" Text="Yes" OnClick="ButtonYes_Click" /><input id="ButtonNo"
type="button" value="No"
onclick="return HidePopupPanel('PanelPopup', '<%= PanelPopup.ClientID %>');" />
</div>
</asp:Panel>
The modalPopup CSS...
.modalPopup{
//Other CSS
left:50%;
margin-left:-100px;
top:50%;
margin-top:-30px;
}
The CSS above sets the left edge of the panel to be aligned with the center of the browser and then adjusts the left margin of the panel by subtracting 100 pixels (which happens to be half of the panel's width.) This centers the panel horizontally. In the same way, the panel is centered vertically by setting the top of the panel to the middle of the screen and then adjusting the top margin by subtracting 30 pixels which is half of the panel's height.
You can do a lot of fun stuff by using this technique. Setting the left, top, right or bottom of a control and then modifying the margins. Play around with it...