答案 0 :(得分:1)
要使蓝框居中,其位置必须设为position:absolute;
如果您的蓝框动态更改大小,则必须使用javascript对其进行居中。
这是一个简单的例子:
$('#color')
.css('top','50%')
.css('left','50%')
.css('margin-left','-'+($('#color').outerWidth()/2)+'px')
.css('margin-top','-'+($('#color').outerHeight()/2)+'px');
确保它在浏览器调整大小时保持中心位置:
$(document).bind('resize', function(){
$('#color')
.css('top','50%')
.css('left','50%')
.css('margin-left','-'+($('#color').outerWidth()/2)+'px')
.css('margin-top','-'+($('#color').outerHeight()/2)+'px');
});
将中心代码包装到函数中并在蓝框大小发生变化时调用它可能是个好主意。
这是编辑过的jsFiddle:
答案 1 :(得分:0)
css中心元素的基础知识:
body
级别(位于屏幕中间的中间位置)position: relative
position: absolute
width
和height
添加到元素top: 50%
和left: 50%
margin-left
和margin-top
分别设为width
和height
的负半部同样的逻辑适用于jQuery,只是你可以动态地计算维度和边距。