孩子<div>
应具有以下 CSS 属性
position: relative;
width: 500px;
height: 500px;
left: 50%;
margin-left: -250px; /* -(width/2) */
top: 50%;
margin-top: -250px; /* -(height/2) */
因此,如果您通过 jQuery 更改子 div,那么您必须重新计算边距...
JSFiddle
http://jsfiddle.net/gvee/fzAge/5/
初始化的 CSS
#edit
{
overflow: hidden;
}
#containment
{
background-image: url(http://placekitten.com/500/500);
position: relative;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -250px;
}
jQuery
$('#edit').click(function() {
var newWidth = 100 + Math.floor(Math.random() * 500);
var newHeight = 100 + Math.floor(Math.random() * 500);
// Resize the child div
$('#containment').width(newWidth).height(newHeight);
// Let's assign a new background too, eh!
$('#containment').css({'background-image': 'url(http://placekitten.com/' + newWidth + '/' + newHeight + ')'});
// Now re-calculate the margins...
var newLeftMargin = (newWidth / -2);
var newTopMargin = (newHeight / -2);
$('#containment').css({'margin-left': newLeftMargin, 'margin-top': newTopMargin});
});