我有一个 div (
#containment
) 位于另一个 div (#edit
) 中。 外部 div 较小。 内部 div 的大小将被一些 jQuery 代码更改。
我想让内部 div 始终在外部 div 内部居中。
<div id="edit"><div id="containment"></div></div>
#edit {
width:200px;
height:200px;
overflow:visible;
margin-top:100px;
background:gray;
}
#containment {
width:500px;
height:500px;
opacity:0.5;
background:red
}
我该怎么做?
#containment{
width:500px; height:500px; opacity:0.5; background:red;
position : absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
通过使用
transform
,您不依赖于父容器的宽度和高度。
请参阅 caniuse 了解浏览器支持。
属性
left
和 top
将元素的左上角设置为父元素的中心。通过使用 translate
,它将 X 和 Y 位置向后移动其自身尺寸的 50%。
您可以在
developer.mozilla.org - 转换 上找到有关transform
的更多信息
是的。你可以做到的。
#edit{
width:200px;
height:200px;
overflow:visible;
margin:200px 0 0 200px;
background:gray;
position : relative;
}
#containment{
width:500px;
height:500px;
opacity:0.5;
background:red;
position : absolute;
top : -150px;
left : -150px;
}
子项
<div>
应具有以下 CSS 属性
position: relative;
width: 500px;
height: 500px;
left: 50%;
margin-left: -250px; /* -(width/2) */
top: 50%;
margin-top: -250px; /* -(height/2) */
因此,如果您通过 jQuery 更改子 div,则必须重新计算边距...
http://jsfiddle.net/gvee/fzAge/5/
#edit
{
overflow: hidden;
}
#containment
{
background-image: url(http://placekitten.com/500/500);
position: relative;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -250px;
}
$('#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});
});