centering with absolute positioning WITHOUT knowing width or height
.hiddenBox {
position: absolute;
left: 50%;
transform: translateX(-50%)
}
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.
You can do it with a parent div
and common CSS properties. It has the advantage to work everywhere, no JS or flexbox required :
<div id="parent">
<div id="child">Hello, I am div !</div>
</div>
<style>
#parent {
position: relative;
width: 100%;
text-align: center;
}
#child {
display: inline-block;
}
</style>
You can do it with javascript. Dynamically get width and height of .hiddenbox
and properly position it using technique you are familiar with. There's one more option to play with, check the example here:
body {
margin: 0;
}
#fade {
background: #ccc;
width: 600px;
height: 200px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
#content {
background: #fff;
border: 1px solid #ff0000;
padding: 20px;
display: inline-block;
}
<div id="fade">
<div id="content">
Something goes here...
</div>
</div>
View on jsFiddle
But in this example you need to know the exact width and height of parent container (.hiddenBg
in your case), it won't work with % units.
If you are ok to use javascript for this task - tell us and possibly add javascript
tag to your question. We can help you with that part of js code.