Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

前端 未结 5 1987
甜味超标
甜味超标 2020-12-12 13:38

I have in my page a button which when clicked displays a div (popup style) in the middle of my screen.

I am using the following CSS to center the

5条回答
  •  遥遥无期
    2020-12-12 13:48

    I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;

    It works and it's cross browser compatible.

    Check out the code below, you probably get a better explanation:

    jQuery('.close a, .bg', '#message').on('click', function() {
      jQuery('#message').fadeOut();
      return false;
    });
    html, body {
      min-height: 100%;
    }
    
    #message {
      height: 100%;
      left: 0;
      position: fixed;
      top: 0;
      width: 100%;
    }
    
    #message .container {
      height: 60%;
      left: 50%;
      position: absolute;
      top: 50%;
      z-index: 10;
      width: 60%;
    }
    
    #message .container .text {
      background: #fff;
      height: 100%;
      left: -50%;
      position: absolute;
      top: -50%;
      width: 100%;
    }
    
    #message .bg {
      background: rgba(0, 0, 0, 0.5);
      height: 100%;
      left: 0;
      position: absolute;
      top: 0;
      width: 100%;
      z-index: 9;
    }
    
    

    Warning

    The message

    Close Window

提交回复
热议问题