较大的div位于较小的div内

时间:2013-08-06 13:50:42

标签: css

我在另一个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
}

fiddle

我该怎么做?

3 个答案:

答案 0 :(得分:20)

Updated Fiddle

#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 :(得分:3)

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

答案 2 :(得分: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;
}

演示:http://jsfiddle.net/fzAge/2/

相关问题