CSS:垂直居中的位置:绝对div

时间:2012-03-02 21:13:53

标签: jquery html css alignment

我有这段代码:

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

父级应为200px宽度和高度,子级为100px宽度和高度。父级也设置为position:absolute。是否有可能将child相对于parent以及如何进行水平和垂直居中?

结果:如果您将黑色背景设置为父级,而将白色设置为该子级,则整个事物应该看起来像是一个带有黑色大边框的白色方块。

静态边距和填充是不可能的,因为孩子的大小会动态变化。


这可能不是正确的解决方案,但我实际上想要实现的是一个黑色方块,我可以用jQuery改变它的大小,它将保持在相同的绝对位置,就像它从中心缩放,而不是从左上角。

我以为我可以设置一个父母的位置,并让孩子在改变它的大小的同时自动地中心和垂直自动,所以我会得到正确的“尺度”效果。

3 个答案:

答案 0 :(得分:1)

由于您编辑了帖子以包含jQuery:

   var c = $('.child'),
       cw = c.width(),
       ch = c.height(),
       hh = ch/2;

c.css({'position' : 'relative' , 'top' : '50%' , 'margin' : '0 auto' , 'margin-top' : '-' + hh + 'px' });

jsfiddle here

调整每个div的高度和宽度,然后重新运行以查看它的实际效果。

答案 1 :(得分:1)

我使用jQuery UI position API将子div定位在中心,然后根据border-width定位.animate,您应相应地更改topleft

试用DEMO了解以下代码 DEMO

动画后:

enter image description here

<强> HTML:

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

<button>Animate</button>

<强> JS:

$(document).ready (function () {
    positionChild();
});


function positionChild() {
    $( ".child" ).position({
                of: $( ".parent" ),
                my: "center center",
                at: "center center"
    });
}

$('button').click (function () {
    $('.child').animate({'border-width': 47, top: '-=46', left: '-=46'}, 1000);
});

<强> CSS:

.parent { 
    position: absolute;  
    width: 200px; 
    height: 200px; 
    background-color: black; 
    top: 100px; 
    left: 100px; 
}

.child { 
    width: 100px; 
    height: 100px; 
    background-color: #c2c2c2; 
    border: 1px solid blue;
}

答案 2 :(得分:0)

line-height:200px设置为父级,将display:inline-block设置为子级。您需要将line-height: 20px或其他内容设置为vertical-align:middle给孩子。

jsFiddle DEMO

看看这段代码:

.parent{
    position:absolute; 
    height:200px; 
    width:200px; 
    background:red;
    line-height:200px;
    text-align:center;
}
.child{
    background:blue; 
    width:100px; 
    height:100px; 
    display:inline-block;
    vertical-align:middle;
    line-height:20px;  /* or something else  */
}