center aligning a fixed position div

前端 未结 13 589
走了就别回头了
走了就别回头了 2020-11-29 15:55

I\'m trying to get a div that has position:fixed center aligned on my page.

I\'ve always been able to do it with absolutely positioned divs using this \

相关标签:
13条回答
  • 2020-11-29 16:18

    From the post above, I think the best way is

    1. Have a fixed div with width: 100%
    2. Inside the div, make a new static div with margin-left: auto and margin-right: auto, or for table make it align="center".
    3. Tadaaaah, you have centered your fixed div now

    Hope this will help.

    0 讨论(0)
  • 2020-11-29 16:19

    Normal divs should use margin-left: auto and margin-right: auto, but that doesn't work for fixed divs. The way around this is similar to Andrew's answer, but doesn't use the deprecated <center> thing. Basically, just give the fixed div a wrapper.

    #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

    This will center a fixed div within a div while allowing the div to react with the browser. i.e. The div will be centered if there's enough space, but will collide with the edge of the browser if there isn't; similar to how a regular centered div reacts.

    0 讨论(0)
  • 2020-11-29 16:20

    If you know the width is 400px this would be the easiest way to do it I guess.

     left: calc(50% - 200px);
    
    0 讨论(0)
  • 2020-11-29 16:20

    This works if you want the element to span across the page like another navigation bar.

    width: calc (width: 100% - width whatever else is off centering it)

    For example if your side navigation bar is 200px:

    width: calc(100% - 200px);

    0 讨论(0)
  • 2020-11-29 16:21

    A solution using flex box; fully responsive:

    parent_div {
        position: fixed;
        width: 100%;
        display: flex;
        justify-content: center;
    }
    
    child_div {
        /* whatever you want */
    }
    
    0 讨论(0)
  • 2020-11-29 16:23

    It is quite easy using width: 70%; left:15%;

    Sets the element width to 70% of the window and leaves 15% on both sides

    0 讨论(0)
提交回复
热议问题