我有这段代码:
<div class="parent">
<div class="child">something</div>
</div>
父级应为200px宽度和高度,子级为100px宽度和高度。父级也设置为position:absolute
。是否有可能将child
相对于parent
以及如何进行水平和垂直居中?
结果:如果您将黑色背景设置为父级,而将白色设置为该子级,则整个事物应该看起来像是一个带有黑色大边框的白色方块。
静态边距和填充是不可能的,因为孩子的大小会动态变化。
这可能不是正确的解决方案,但我实际上想要实现的是一个黑色方块,我可以用jQuery改变它的大小,它将保持在相同的绝对位置,就像它从中心缩放,而不是从左上角。
我以为我可以设置一个父母的位置,并让孩子在改变它的大小的同时自动地中心和垂直自动,所以我会得到正确的“尺度”效果。
答案 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,您应相应地更改top
和left
。
试用DEMO了解以下代码 DEMO
动画后:
<强> 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
给孩子。
看看这段代码:
.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 */
}