如何保持浮动div集中在窗口调整大小(jQuery / CSS) [英] How to keep a floating div centered on window resize (jQuery/CSS)

查看:146
本文介绍了如何保持浮动div集中在窗口调整大小(jQuery / CSS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法(没有绑定到window.resize事件)强制浮动DIV在浏览器窗口调整大小时重新定位自己?

Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?

帮助解释,我想象伪代码看起来像:

To help explain, I imagine the pseudocode would look something like:

div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)

UPDATE

我的查询已经在下面回答,我想发布我的任务的最终结果 - 一个jQuery扩展方法允许您将任何块元素 - 希望它也能帮助别人。

My query having been answered below, I wanted to post the final outcome of my quest - a jQuery extension method allowing you to center any block element - hope it helps someone else too.

jQuery.fn.center = function() {
    var container = $(window);
    var top = -this.height() / 2;
    var left = -this.width() / 2;
    return this.css('position', 'absolute').css({ 'margin-left': left + 'px', 'margin-top': top + 'px', 'left': '50%', 'top': '50%' });
}

用法:

$('#mydiv').center();


推荐答案

fixed-size div:

This is easy to do with CSS if you have a fixed-size div:

.keepcentered {
    position:    absolute;
    left:        50%;        /* Start with top left in the center */
    top:         50%;
    width:       200px;      /* The fixed width... */
    height:      100px;      /* ...and height */
    margin-left: -100px;     /* Shift over half the width */
    margin-top:  -50px;      /* Shift up half the height */
    border: 1px solid black; /* Just for demo */
}

问题当然是固定的-size元素不太理想。

The problem, of course, is that fixed-size elements aren't ideal.

这篇关于如何保持浮动div集中在窗口调整大小(jQuery / CSS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆