首页 文章

中心对齐固定位置div

提问于
浏览
96

我正试图在我的页面上找到一个 position:fixed 居中对齐的div .

我一直能够使用这个“黑客”绝对定位的div来做到这一点

left: 50%; width: 400px; margin-left:-200px

... margin-left的值是div宽度的一半 .

这似乎不适用于固定位置div,而只是将它们的最左边角放置在50%并忽略margin-left声明 .

有关如何解决此问题的任何想法,以便我可以对齐固定定位的元素?

如果你能告诉我一个更好的方法来对齐绝对定位的元素而不是我上面概述的方式,我会投入奖金M&M .

11 回答

  • 133

    如果您希望元素跨越页面(如另一个导航栏),则此方法有效 .

    width:calc(宽度:100% - 其他任何偏离中心的宽度)

    例如,如果您的侧面导航栏是200px:

    宽度:计算(100% - 200px);

  • 155

    将“固定”元素居中的一个好方法是将“中心”元素设置为固定且宽度为100%,其中的所有内容都将位于100%宽度“中心”的中心 .

    css将是:

    #center{
        position:fixed;
        width: 100%; //this basically stretches all over the window as fixed
    }
    

    html将是:

    <html><head></head>
    <body>
        <center id='center'>
            ...elements
        </center>
    </body></html>
    

    相同的方法可以应用于元素的绝对定位 .

    UPDATE: 对于认为中心标记已被弃用的怀疑者,可以使用已应用align = "center"属性的包装div替换它 . 您甚至可以删除对齐,并可以使用text-align:center .

  • 28

    如果你知道宽度是400px,这将是我猜的最简单的方法 .

    left: calc(50% - 200px);
    
  • 7

    如果要在垂直和水平方向上对齐固定位置div,请使用此方法

    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    
  • 0

    Koen的答案并不完全集中于元素 .

    正确的方法是使用 CCS3 transform 属性 . 虽然它是not supported in some old browsers . 我们甚至不需要设置固定或相对的 width .

    .centered {
        position: fixed;
        left: 50%;
        transform: translate(-50%, 0);
    }
    

    工作jsfiddle比较here .

  • 0

    我在Twitter Bootstrap(v3)中使用了以下内容

    <footer id="colophon" style="position: fixed; bottom: 0px; width: 100%;">
        <div class="container">
            <p>Stuff - rows - cols etc</p>
        </div>
    </footer>
    

    即,制作一个固定位置的全宽度元素,然后将容器推入其中,容器相对于整个宽度居中 . 也应该表现得很好 .

  • 1

    使用宽度非常容易:70%;左:15%;

    将元素宽度设置为窗口的70%,并在两侧留下15%

  • 3

    对于具有相同问题但具有响应式设计的人,您还可以使用:

    width: 75%;
    position: fixed;
    left: 50%;
    margin-left: -37.5%;
    

    即使采用快速响应设计,这样做也始终将固定 div 保持在屏幕中心 .

  • 2

    从上面的帖子,我认为最好的方法是

    • width: 100% 的固定div

    • 在div中,使用 margin-left: automargin-right: auto 创建一个新的静态div,或者为表创建 align="center" .

    • Tadaaaah,你现在已经集中了你的固定div

    希望这会有所帮助 .

  • 29

    普通div应该使用 margin-left: automargin-right: auto ,但这对固定的div不起作用 . 解决这个问题的方法类似于Andrew's answer,但不使用已弃用的 <center> 事物 . 基本上,只需给固定div一个包装器 .

    #wrapper {
        width: 100%;
        position: fixed;
        background: gray;
    }
    #fixed_div {
        margin-left: auto;
        margin-right: auto;
        position: relative;
        width: 100px;
        height: 30px;
        text-align: center;
        background: lightgreen;
    }
    
    <div id="wrapper">
        <div id="fixed_div"></div>
    </div
    

    这将使div中的固定div居中,同时允许div与浏览器做出反应 . 即如果有足够的空间,div将居中,但如果没有,则会与浏览器的边缘发生碰撞;类似于常规居中的div如何反应 .

  • 1

    使用柔性盒的解决方案;完全响应:

    parent_div {
        position: fixed;
        width: 100%;
        display: flex;
        justify-content: center;
    }
    
    child_div {
        /* whatever you want */
    }
    

相关问题