I am creating an overlay. There is a div that coats the whole page in 50% transparent black. Another div must be centered, vertically and horizontally to the screen. It must be absolutely positioned. Is there anyway to do this without knowing the height/width? It will change based on screen res. I am familiar with the absolute positioning centering techniques when you know the height and width, (i.e. left: 50%; margin-left: -150px; top: 50%; margin-top: -300px;)... But again, can I do this without knowing the height/width? Here is the code:
.hiddenBg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: black;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
z-index: 10000;
/*display: none;*/
}
.hiddenBox {
position: absolute;
left: 50%;
margin-left: -200px;
top: 50%;
margin-top: -100px;
width: auto;
height: auto;
background-color: #FF7F00;
border: solid 10px white;
z-index: 10001;
text-align: center;
/*display: none;*/
}
Just stumbled upon this old question. I think you have two different possibilities to do this (browser support is growing) with CSS only now, no JavaScript required:
1. Do it with flexbox
<div class="hiddenBg">
<div class="hiddenBox">
Hello
</div>
</div>
<style>
.hiddenBg {
display: flex;
align-items: center;
justify-content: center;
}
</style>
2. Absolute + negative transform translate
.hiddenBox {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
In the first three lines the object will be placed in the middle of the parental container with top
and left
set to 50%
. Unfortunately this applies to the top left corner of the object. So it will not appear to be visually centered. The fourth line corrects that by transforming the centered point to the middle of the object. Mind that the parental container of this needs to be positioned relative.