jquery - CSS,jquery 水平对齐中的固定标题

标签 jquery css

我有一个 jquery 的问题,我制作了一个固定的标题,但是当它向下滚动时它没有水平对齐。在 CSS 中,我把 margin-left:auto;margin-right:auto;它做得对,但是当我向下滚动时,标题会转到左侧。

我不知道是 jquery 还是 CSS 的问题。

非常感谢。

这是我的 jQuery:

$(function () {
    var HeaderTop = $('#header').offset().top;
    $(window).scroll(function () {
        if ($(window).scrollTop() > HeaderTop) {
            $('#header').css({
                position: 'fixed',
                top: '0px',
                marginLeft: 'auto',
                marginRight: 'auto'
            });
        } else {
            $('#header').css({
                position: 'relative',
                top: '0px'
            });
        }
    });
});

我的 CSS:

    html, body
    {
        height:100%;
    }
    body
    {
        margin: 0;
        padding: 0;
    } 
    #header
    {
        width:900px;
        height:100px;
        background-color:#FFF;
        margin-left:auto;
        margin-right:auto;
        border-top:1px;
        border-top-color:#D2D2D2;
        border-top-style:solid;
        border-bottom:1px;
        border-bottom-color:#D2D2D2;
        border-bottom-style:solid;
    }
    header
    {
        background-color:#FFF;
        width:900px;
        margin-left:auto;
        margin-right:auto;
        text-align:center;
    }
    .content
    {
        width:900px;
        margin-left:auto;
        margin-right:auto;
    }
    #header ul
    {
        list-style:none;
    }
    #header ul li
    {
        display:inline;
        padding:10px;
    }

我的 HTML:

    <header>
    <img src="darkness.png" height="100" />
    </header>
    <div id="header">
    <ul>
    <li>Home</li><li>About</li>
    </ul>
    </div>
    <div class="content">
    </div>

jsFiddle 演示: http://jsfiddle.net/24ba7

最佳答案

您甚至不需要为此使用 JQuery。

You just need CSS (click for live example):

 #header {
        position:fixed;
        width:900px;
        height:100px;
        left: 50%;
        margin-left: -450px;
    }

Fullscreen version.

稍微解释一下,负边距是您定义的宽度的一半,因为元素基于其最左上角的点在页面上居中,因此我们通过将其向后移动一半来补偿这一点。

固定定位默认对齐到最左边和最上面,所以 centering a fixed element需要一点按摩。

但是如您所见,这是一个 CSS 解决方案,所以除非您需要使用 JQuery,否则我会避免使用它。对于可以用纯 CSS 完成的事情,它增加了不必要的开销和复杂性。


JQUERY 解决方案

http://jsfiddle.net/24ba7/7/

    if ($(window).scrollTop() > HeaderTop) {
        $('#header').css({
            position: 'fixed',
            top: '0px',
            left:'50%',
            marginLeft: '-450px'
        });

你不能使用 auto marginfixed 定位,你需要使用我建议的 margin fix。

关于jquery - CSS,jquery 水平对齐中的固定标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532872/

相关文章:

用于文档前导零和从右到左的 jQuery 掩码

jQuery 如何让图像在加载时淡入?

javascript - jQuery(附加、分离、重新附加)事件处理程序问题

Javascript - setInterval、动画、延迟

html - CSS 相对位置 : width not considered

javascript - 如何使用ajax json制作morris donut chart ?

javascript - Bootstrap3切换开关与ajax更新到mysql

html - Bootstrap 轮播中的垂直居中文本

html - 视差图像顶部的透明文本 div

html - 需要帮助对齐另一个 div 内的 div。需要他们在右边