center aligning a fixed position div

前端 未结 13 645
走了就别回头了
走了就别回头了 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: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

    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;
    }

    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.

提交回复
热议问题