need help CSS centering with absolute positioning

后端 未结 9 1196
庸人自扰
庸人自扰 2021-02-14 07:41

I\'ve never been totally satisfied with my various solutions to centering content in a web page. the

tag has been deprecated back in the middle of th
9条回答
  •  北恋
    北恋 (楼主)
    2021-02-14 08:16

    If you're sticking with position: absolute; then set the div that you want things positioned against to have position: relative; to make it into the positioning context for any child elements.

    To center an absolutely positioned div you need to know it's width, then use the following CSS:

    #wrapper {
        width: 800px;
        margin: 0 auto;
        position: relative; /* creates a positioning context for child elements */
    }
    
    #child {
        position: absolute;
        width: 400px;
        left: 50%;
        margin-left: -200px;
    }
    

    And the HTML:

    ....

    You can tweak the width and left margin as you need it (the negative left margin should be half of the width of the div you are centering eg. #child.

    As other people have mentioned using margin: 0 auto; on an element with a width set on it will center it.

提交回复
热议问题