Show Div In The Center Of Current Viewport On Mobile Devices
How do you show a div in the center of the current viewport? I am asking specifically for mobile devices, because they are the most problematic. For example, I have 2 buttons that
Solution 1:
Use position: fixed
.
function toggleDiv() {
var div = document.getElementById('togglable');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
#container-parent {
position: absolute;
background-color: #eee;
height: 95%;
width: 90%;
overflow: scroll;
}
#container {
height: 500px;
}
#togglable {
position: fixed;
top: 10%;
height: 80%;
left: 25%;
width: 50%;
background-color: red;
}
#spacer {
height: 90%;
}
<div id="container-parent">
<div id="container">
<input type=button onclick="toggleDiv()">
<div id="togglable"></div>
<div id="spacer">
<!-- I don't know how you have got your buttons attached but the point is that `position: fixed` positions the togglable div relative to the viewport -->
</div>
<input type=button onclick="toggleDiv()">
</div>
</div>
Solution 2:
Please use display:flex
for the main container and the stylesheet would look something like :
display:flex;
flex-direction: column; //to align them vertically
justify-content:center;
align-items: center; //centers out the whole elements horizontally.
Post a Comment for "Show Div In The Center Of Current Viewport On Mobile Devices"