Home > other >  How can I position a modal element in the center of the viewport?
How can I position a modal element in the center of the viewport?

Time:01-31

I'm trying to create a button that when clicked brings up a pop up window with an iframe source embedded.

However, at the moment the iframe shows up right below the button when clicked. What I need is for the iframe to show up as a window in the center of the screen.

$(function() {
  $('#button').click(function() {
    if (!$('#iframe').length) {
      $('#iframeHolder').html('<iframe id="iframe" src="https://fixr.co/event/831401916?compact=true&theme=dark" width="700" height="450"></iframe>');
    }
  });
});
<button id="button">Button</button>
<div id="iframeHolder"></div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>

CodePudding user response:

It's just a matter of positioning your iframe container relative to the viewport. There are many ways of doing this, and the best one depends on what else is happening in your page. Here's a solution assuming that the page appears just as you've shown it. See the full page demo for a better view.

Protip: Update your jQuery version. 1.x is very old. You can often update to 3.x with no code changes. Of course, if this is all you're using it for you don't really need jQuery anyway.

$(function() {
  $('#button').click(function() {
    if (!$('#iframe').length) {
      $('#iframeHolder').html('<iframe id="iframe" src="https://fixr.co/event/831401916?compact=true&theme=dark" width="700" height="450"></iframe>');
    }
  });
});
body {
  position: relative;
  min-height: 100vh;
}

#iframeHolder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<button id="button">Button</button>
<div id="iframeHolder"></div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>

CodePudding user response:

Getting this right might be dependent on some of what's going on in the rest of the page, but this CSS should get the pop-up div centered for you.

#iframeHolder{
  display: flex;
  justify-content: center;
}
  • Related