较大的 div 位于较小的 div 的中心

问题描述 投票:0回答:4

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

小提琴

我该怎么做?

css
4个回答
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 了解浏览器支持。

属性

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

您可以在

developer.mozilla.org - 转换 上找到有关 transform

的更多信息

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/


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

0
投票

新小提琴

对于那些在 2024 年及以后的遥远未来偶然发现这个主题的人,您可能想使用 CSS 网格布局 来解决这个问题。您只需要父元素上的以下三种样式,在本例中为“编辑”div。

  display: grid;
  align-content: center;
  justify-content: center;
© www.soinside.com 2019 - 2024. All rights reserved.