How to place DIV on top of all and on the middle of page?
Use a slightly different markup and css to position both your overlay and your popup.
Build a simple markup like this:
<form id="form1" runat="server">
...
</form>
<div id="overlay"></div>
<div id="popup">Popup</div>
Notice I haven't put the popup within the overlay. While there is no hurt to do this, if you want to style your overlay with css opacity, everything contained in it will also be semi-transparent.
Then use the following CSS:
#overlay {
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
width:100%;
height:100%;
z-index:998;
background-color: Black;
opacity: .5;
}
#popup {
position: absolute;
width:50%;
background-color:#8DA5C6;
z-index: 999;
}
- Both elements must have
position: absolute
to go out of the page flow. - The overlay must cover the whole space. This is achieved with
top, left, right, bottom, width, height
- Using
z-index
, you can then make them stay on top of other things. A lower one for the overlay and a higher one for the popup
You can check this fiddle for a working example.
Note:
This does not center the popup. It requires a bit more work to do so and it's a bit more complex (has the popup a fixed size or not, should the popup stay centered while resizing the window...).
It would require a bit of javascript I guess.
You can't use margin: 0 auto;
on absolute positionned elements.
Comments
-
MichaelS almost 2 years
I have a page with a
form
and adiv
:<body> <form id="form1" runat="server"> ... </form> <div id="wizardDiv" style="width: 100%; height: 100%;background-color:black;display:none"> <div style="background-color:#8DA5C6; z-index:999; width: 50%; margin: 0 auto;"> ... </div> </div> </body>
On a button click, I make the
div
visible, and I want it to cover the whole page, while the innerdiv
is right in the middle (in the center, both horizontally and vertically.) just like a popup modal.To illustrate:
The current html fails the following:
- The
div
is not covering the whole page, it is located after theform
, instead overlaying it. - The inner
div
is only horizontally centered and not vertically.
What am I missing here?
Is my approach is "browser-compatibility" safe? (Maybe I should look for a Jquery solution?)
Final Solution:
I ended up using:
- Didier G answer for the overlay problem.
- Jquery to center the div on screen
- CSS3 for rounding the corners of the div
- The
-
Didier Ghys over 12 yearsI wonder how can jquery be necessary to style correctly two
<div>
with pure css... jQuery is not the solution to everything. -
Ariona Rian over 12 yearsG, adding position:absolute make it ugly when user scroll down the page, the div will follow the page not covering the whole page again. so you need to position:absolute this