How to center align pop up div using Javascript

前端 未结 5 915
借酒劲吻你
借酒劲吻你 2020-12-14 22:58

How to align a pop up division to center of monitor/screen using javascript?

I tried using screen.width and screen.height to get center. But the division gets aligne

相关标签:
5条回答
  • 2020-12-14 23:37

    try:

     function msgBox(message)
     {
      var msgbox = document.getElementById("msgbox");
      msgbox.innerHTML = message;
      var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2);
      var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);              
      msgbox.style.top = y;
      msgbox.style.left = x;
      msgbox.style.display = "block";
     }
    
    0 讨论(0)
  • 2020-12-14 23:39

    Try fixed-positioning:

    #box {
      position: fixed;
      width: 40%;
      margin: 200px 30%;
    }
    

    It's only horizontally centered. Vertical will take some playing with. I have no idea how browsers act differently with the vertical alignment.

    0 讨论(0)
  • 2020-12-14 23:42

    I also had this vertical centering problem on any webpage that required scrolling.

    Switching to position: fixed solved it, so:

    position:fixed;
    top:50%;
    left:50%;
    margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
    

    This worked in firefox, google chrome, safari (pc) and IE9.

    Unfortunately, I wanted it to appear in front of an pdf file - the pop up did appear in front using Firefox, Chrome but went behind in IE9 and Safari....

    0 讨论(0)
  • 2020-12-14 23:53

    Try this:

    <div id="popup" class="popup">
      This a vertically and horizontally centered popup.
    </div>
    
    <a onclick="showPopup('popup');">Show Popup</a>
    
    <style type="text/css">
      .popup {
        width:200px;
        height:100px;
        position:absolute;
        top:50%;
        left:50%;
        margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
        display:none;
      }
    </style>
    
    <script type="text/javascript">
      function showPopup(id) {
        var popup = document.getElementById(id);
        popup.style.display = 'block';
      }
    </script>
    

    CSS explained: The div is 200x100, you position it 50% from the top and 50% from the left, but to have it centered fully, you need to substract from that 50% values the half of the width and height, the way to do this is to use negative margins, hence margin-top should be the negative value of the height/2 and margin-left should be the negative value of the width/2.

    0 讨论(0)
  • 2020-12-14 23:56

    How about just doing with CSS:

    <div class="div">Some Content......</div>
    
    .div {
       margin-left: auto;
       margin-right: auto;
    }
    
    0 讨论(0)
提交回复
热议问题