更大的div居中放置在较小的div内部。

15

我在一个div元素中(id为#edit),还嵌套了另一个div元素(id为#containment)。外部的那个div比较小。通过jQuery代码,内部div元素的大小会被改变。

我希望始终让内部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
}

fiddle

我该如何做到这一点?


#containment总是500x500吗? - j08691
编辑 div 始终是 200x200,容器将根据用户的图像而改变。 - Ben
3个回答

29

更新的示例

#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查看浏览器支持情况。

属性lefttop将元素的左上角设置为父元素的中心。 通过使用translate,它将X和Y位置向后移动其自身尺寸的50%。

您可以在developer.mozilla.org-transform上找到有关transform的更多信息。


1
非常好。我不知道这个新的CSS3属性! - gvee

2

是的,您可以这样做。

#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;
}

Demo: http://jsfiddle.net/fzAge/2/


位置:绝对;移动编辑div的位置,是否不会影响父div? - Ben
任何绝对定位的元素始终相对于其偏移父元素。偏移父元素是具有位置值而非默认值(static)的元素。为了确保包含 div 相对于编辑 div,我向编辑 div 添加了一些边距。 - Sasidhar Vanga

2
孩子元素 <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});
});

子div的大小会改变,因此这不适用。 - Brigand
我只是在阐述理论。现在我会加入jQuery的内容来更新我的答案。 - gvee
margin-left: -250px; /* 因为子元素始终为500像素,永远不会改变 */ 我们什么时候才能消除这样的硬编码尺寸?几乎每次我写硬编码尺寸,都必须回来将其更改为某些灵活的东西,以使网站具有响应性。 “子div将更改大小”不应该被说出来。默认情况下,元素会更改大小(即使为了最小示例,我们在元素上添加了“宽度”和“高度”)。元素不改变大小是特殊情况! - lmat - Reinstate Monica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接