How to center a “position: absolute” element

后端 未结 26 3254
-上瘾入骨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:16

    Without knowing the width/height of the positioned1 element, it is still possible to align it as follows:

    EXAMPLE HERE

    .child {
        position: absolute;
        top: 50%;  /* position the top  edge of the element at the middle of the parent */
        left: 50%; /* position the left edge of the element at the middle of the parent */
    
        transform: translate(-50%, -50%); /* This is a shorthand of
                                             translateX(-50%) and translateY(-50%) */
    }
    

    It's worth noting that CSS Transform is supported in IE9 and above. (Vendor prefixes omitted for brevity)


    Explanation

    Adding top/left of 50% moves the top/left margin edge of the element to the middle of the parent, and translate() function with the (negative) value of -50% moves the element by the half of its size. Hence the element will be positioned at the middle.

    This is because a percentage value on top/left properties is relative to the height/width of the parent element (which is creating a containing block).

    While a percentage value on translate() transform function is relative to width/height of the element itself (Actually it refers to the size of bounding box).

    For unidirectional alignment, go with translateX(-50%) or translateY(-50%) instead.


    1. An element with a position other than static. I.e. relative, absolute, fixed values.

提交回复
热议问题