How to center a “position: absolute” element

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

    #parent
    {
        position : relative;
        height: 0;
        overflow: hidden;
        padding-bottom: 56.25% /* images with aspect ratio: 16:9  */
    }
    
    img 
    {
        height: auto!important;
        width: auto!important;
        min-height: 100%;
        min-width: 100%;
        position: absolute;
        display: block;
        /*  */
        top: -9999px;
        bottom: -9999px;
        left: -9999px;
        right: -9999px;
        margin: auto;
    }
    

    I don't remember where I saw the centering method listed above, using negative top, right, bottom, left values. For me, this tehnique is the best, in most situations.

    When I use the combination from above, the image behaves like a background-image with the following settings:

    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-size: cover;
    

    More details about the first example can be found here:
    Maintain the aspect ratio of a div with CSS

提交回复
热议问题