How to center a “position: absolute” element

后端 未结 26 3244
-上瘾入骨i
-上瘾入骨i 2020-11-21 05:35

I\'m having a problem centering an element that has the attribute position set to absolute. Does anyone know why the images are not centered?

<
26条回答
  •  误落风尘
    2020-11-21 06:05

    What seems to be happening is there are two solutions; centered using margins and centered using position. Both work fine, but if you want to absolute position an element relative to this centered element, you need to use the absolute position method, because the absolute position of the second element defaults to the first parent that is positioned. Like so:

    
    

    width: 300 px; margin: 0 auto

    Absolute

    width:300px; position: absolute; left: 50%; margin-left:-150px;

    Absolute

    Until I'd read this posting, using the margin:0 auto technique, to build a menu to the left of my content I had to build a same-width column to the right to balance it out. Not pretty. Thanks!

提交回复
热议问题