【问题标题】:Centering webpages horizontally and vertically with jQuery使用 jQuery 将网页水平和垂直居中
【发布时间】:2011-09-23 20:37:26
【问题描述】:

谁能告诉我这段代码有什么问题?我正在尝试将我的网页垂直和水平居中,但这不起作用!它不是以我为中心。

<html>
<head>
    <title>String Functions</title>
    <script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
    <script type="text/javascript">
    jQuery.fn.center = function() {
     this.css("position", "absolute");
     this.css("top", ($(document).height() - this.height()) / 2 + $(document).scrollTop() + "px");
     this.css("left", ($(document).width() - this.width()) / 2 + $(document).scrollLeft() + "px");
    return this;
    };

    $("#d1").center();
    </script>       
</head>

<body>

<div id="d1" style="background-color:red;width:100px; height: 100px;"></div>    

</body>

【问题讨论】:

  • 您遇到了什么问题?我没有看到...我将窗口更改为文档。 jsfiddle.net/euALd
  • 你好,它根本不适合我。上面的代码就是我所拥有的。
  • 它也对我有用。你使用的是什么浏览器?控制台会报错吗?
  • 你好,我试过firefox、safari,但没有运气也没有错误!
  • 真的吗???我在 firefox、IE8 和 chrome 中尝试过,它们都可以通过我上面提供的链接渲染得很好! jsfiddle.net/euALd

标签: jquery css centering


【解决方案1】:

试试这个。

jQuery.fn.center = function() {
    this.css({
        "position" : "absolute",
        "top" : "50%",
        "left" : "50%",
        "margin-left" : (this.width() / 2) * -1,
        "margin-top" : (this.width() / 2) * -1
    });
};

将绝对定位元素居中的一种非常可靠的方法是将其位置从左侧或顶部设置为 50%,然后将其边距设置为对象宽度或高度的一半。

【讨论】:

    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 2023-03-30
    • 2012-05-09
    • 2018-03-10
    • 2022-01-09
    • 2015-07-21
    • 2019-07-19
    相关资源
    最近更新 更多