I was trying to create a modal window which will be displayed in desktop browsers, mobile browser and tablets.
I want to make the absolute position of div at the same time, div should be in center of page in horizontal and vertical.
I tried the following
#outerdiv{
top: 50%;
left: 50%;
position: fixed;
width:100%;
margin-left:0px;
}
#innerdiv{
width:50%;
height:100%
}
The above code auto fit the content to page. But how to make absolute position or center align in horizontal and vertical. I was displaying this div like a pop up.
I was trying to create a modal window which will be displayed in desktop browsers, mobile browser and tablets.
I want to make the absolute position of div at the same time, div should be in center of page in horizontal and vertical.
I tried the following
#outerdiv{
top: 50%;
left: 50%;
position: fixed;
width:100%;
margin-left:0px;
}
#innerdiv{
width:50%;
height:100%
}
The above code auto fit the content to page. But how to make absolute position or center align in horizontal and vertical. I was displaying this div like a pop up.
Share Improve this question edited Sep 5, 2021 at 7:21 Super BUFF Meatballs 2251 silver badge13 bronze badges asked Jan 10, 2014 at 4:36 Pandiyan CoolPandiyan Cool 6,5858 gold badges53 silver badges90 bronze badges4 Answers
Reset to default 3This solution should scale gracefully with window size, and on resize too. We give the parent the width and height of the window like so:
body{
height:100%;
width:100%;
}
Then we specify the containing div to:
- Have half the height and width
- Pad the top and bottom by a quarter (a half of the space taken up)
Like so:
#innerdiv{
position:fixed;
width:50%;
height:50%;
top:25%;
margin-left:25%;
border: 1px black solid;
}
jsFiddle here: jsFiddle
To center align a div horizontally, the best trick I believe is:
left:50%;
margin-left:-"half the width"px;
For vertical alignment I would go with JavaScript and calculate the height of the screen
var height = $(window).height();
var div_height = $('#div').height();
$('#div').css('top', (height - div_height) / 2);
You could of course also apply this to a parent element by changing "window" to the parent.
Assuming the following html structure:
<body>
<div id="yourDiv">
<!-- modal content -->
</div>
</body>
You can center your container with the following styles:
#yourDiv {
display: inline-block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 500px;
height: 500px;
}
Note: you'll need to give your container a height and width for the centering to work.
Here's a Fiddle.
I would go for a fixed size of the .popup
.
.popup {
height: 300px;
width: 300px;
position: fixed;
top: 50%;
left: 50%;
margin: -150px;
}