Good day.
I know that if you want to absolute center a div, you do this:
blahblah
This can be done with CSS alone.
#parent {
position: absolute;
max-width: 500px;
max-height: 500px;
width: 100%;
height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
See demo https://jsfiddle.net/matharden/8kmvt8qd/
As the width
and height
are fluid, you need to go with javascript or jQuery. Just add the below code in head
tag. (The below example is in javascript)
<script>
window.onresize = function(){
//To work even on resize
getToMiddle();
}
window.onload = function(){
getToMiddle();
}
function getToMiddle(){
var box = document.getElementById('parent');
var height = box.offsetHeight;
var width = box.offsetWidth;
box.style.top = -(height/2);
box.style.left = -(width/2);
}
</script>
and your css would be something like this:
#parent{
max-width: 500px;
max-height: 500px;
background-color:green;
position:absolute;
top: 50%;
left: 50%;
/* width: 10%;
height: 10%; */
}
To test, give width: 10%; and height: 10%
Working Fiddle
I'll simply use flex
to achieve this...
#parent {
display: flex;
justify-content: center;
}
<div id="parent">
<div id="child">blahblah</div>
</div>