sanjihan sanjihan - 10 months ago 48
CSS Question

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 show the same div. One at top of the page, and one at the bottom. The page's height is 2 viewport heights in total. If the padding-top of the presented div is 40px, then the div will not be visible when the bottom button is being pressed. Clearly this solution isn't flexible enough for mobile devices.
What solution do you recommend?

DIAGRAM: If i set the padding-top to 40px, the green div will appear at the top of the page (as shown) If the bottom red button is pressed, the green div will also appear at the top, 40px from it. It isn't even visible to the user. It should appear 40px from the top of the second viewport (the screen that users sees.) I hope that helps.

enter image description here

Answer Source

Use position: fixed.

function toggleDiv() {
    var div = document.getElementById('togglable');
    if ( !== 'none') { = 'none';
    else { = '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 -->
    <input type=button onclick="toggleDiv()">