将元素直接置于屏幕中心。 jQuery的

时间:2013-03-01 00:31:39

标签: javascript jquery html

只想使用jquery将蓝框直接置于屏幕中央。

的jsfiddle: http://jsfiddle.net/Pxjkk/

<html>

2 个答案:

答案 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:

http://jsfiddle.net/mdkpS/

答案 1 :(得分:0)

css中心元素的基础知识:

  • 为您的元素制作一个容器并将其放在body级别(位于屏幕中间的中间位置)
  • 在容器上设置position: relative
  • 在元素
  • 上设置position: absolute
  • 将固定的widthheight添加到元素
  • 在元素
  • 上设置top: 50%left: 50%
  • margin-leftmargin-top分别设为widthheight的负半部

同样的逻辑适用于jQuery,只是你可以动态地计算维度和边距。