Center a popup with jQuery, CSS, HTML

A simple horizontally and vertically centered popup. Allows you to create several on one page.

Add this jQuery:

jQuery(".popupopen").click(function() {
  box = jQuery(this).attr('rel);
  jQuery('#'+box).show();
  width = -1 * parseInt((jQuery('#'+box).width()/2));
  height = -1 * parseInt((jQuery('#'+box).height()/2));
  jQuery('#'+box).css('margin-left',width).css('margin-top',height);
  return false;
});
jQuery(".popupclose").click(function() {
  jQuery(this).parent().hide();
  return false;
});

Add this HTML:

<p><a title="Open this popup" href="#" class="popupopen" rel="popup1">open a popup</a></p>
<div class="popup" id="popup1">
  <p>My popup insides</p>
  <a title="Close this popup" href="#" class="popupclose">close</a>
</div>

Add this CSS:

.popup { 
  z-index:999; 
  position:fixed; 
  top:50%; 
  left:50%; 
  width:66%;
  max-width:300px;
  padding:20px; 
  display:none;
  text-align:center;  
}

References:

One Reply to “Center a popup with jQuery, CSS, HTML”

  1. thank you your Code ,

    But I found missing

    box = jQuery(this).attr(‘rel); -> jQuery(this).attr(‘rel’);

    ^^ I have lot of situation, too.

Comments are closed.