我在另一个div(#edit)中有一个div(#containment).外部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
- }
我怎样才能做到这一点?
解决方法
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.
左侧和顶部属性将元素的左上边缘设置为父级的中心.通过使用平移,它将X和Y位置移回其自身尺寸的50%.
您可以在developer.mozilla.org – transform上找到有关转换的更多信息