0

看到这个Fiddle,如何在父子节点中没有固定宽度和高度的蓝色 div 居中?

这是张贴在 SO

<div class="parent">
<div class="child">
</div>
</div>

更新

这些是定位元素,我希望孩子位于屏幕的中心。

更新 2

看到它在这里居中,但我不能在父母和孩子中使用固定的宽度或高度。我需要定位元素,因为我需要它们在其他元素之上。

4

5 回答 5

5

要使 div 居中,您只需添加此属性:

margin-left: auto;
margin-right: auto;

或更精简的版本(假设顶部和底部边距为 0px):

margin: 0px auto;

这假设您在要居中的那个元素上有某种宽度值,无论是固定的还是百分比。您不需要父母中的任何东西来决定孩子的边距。

于 2013-04-11T05:11:38.093 回答
1

边距顶部:-50%;/* 为什么这需要父级的宽度????*/

这是因为您的父 div 具有position: fixed并且您的子 div 具有position: absolute并且因为绝对位置元素相对于第一个具有非静态位置的父元素定位。

因此,您的子 div 将采用顶部边距和左侧边距,其值等于-50%您的父宽度,即-50% * 150 = 75px

于 2013-04-11T05:14:17.597 回答
0

试试这个,它显示在宽度的中心。

<div class="parent">
<div class="child">
</div>
</div>
<style type="text/css">
.parent{
}
.child{
    background: none repeat scroll 0 0 lightblue;
    height: 50px;
    margin: 0 auto;
    width: 150px;
}
</style>
于 2013-04-11T05:11:50.917 回答
0

动态模态可能是世界上最大的痛苦。您需要 JS 来更改高度和宽度。可以用插件吗?如果是这样,这里有一些不错的选择。Twitter bootstrap 有一个非常容易设置的模式,但是通过 ajax 和 iframe 加载 div 具有挑战性。你必须选择其中之一。simplemodal ( http://www.ericmmartin.com/projects/simplemodal/ ) 很好,但您仍然需要自己做很多工作。它适用于 iframe 和 ajax 内容。

于 2013-04-11T15:47:26.753 回答
0

我认为这可以解决您的问题,但这需要JQuery[.width()]

.parent{
    position: fixed;    
    /* I can't use static width nor height, TO DELETE(try changing this)*/
    width: 500px;
    height: 400px;
    background: red;    
}

.child{
    display: inline-block;
    position: absolute; 
    /*Simulate width and height, these are actually calculated by content*/
    width: 100px;
    height:50px;
    background: lightblue;   
}

jQuery onLoad:[ JSFiddle ]

$(function changePostion() {
    var s = $(".parent").width(); 
    var e = $(".child").width();   
    var d= (s-e)/2;
    $(".child").css({"left":d}); 
    var sh = $(".parent").height(); 
    var eh = $(".child").height(); 
    var dh= (sh-eh)/2;
    $(".child").css({"top":dh});    
});

本文是在中心定位 html 属性的最佳教程不使用 JQuery 可能有更好的方法。

于 2013-04-11T15:23:25.470 回答