Vertical-align image

前端 未结 7 1218
梦如初夏
梦如初夏 2020-11-29 04:21

I have a div that contains an image and a p tag (seen below). I want to align the image in the middle of the div vertically depending on how many lines the paragraph is. Ver

7条回答
  •  无人及你
    2020-11-29 05:06

    This is pure CSS, vertically aligns the image, and also resizes the image down if it's taller (or wider) than the containing box. Ergo, the box and image can both be any size without breaking the vertical alignment. Also, you may want to add a left margin to the

    tags to keep them from being hidden by the image.

    CSS

    /* Positioning */
    .absoluteCenterWrapper {
        position: relative; /* Contains the image in the div */
    }
    .absoluteCenter { /* Aligns image vertically */
        margin: auto;
        position: absolute;
        top: 0;
        bottom: 0;
    }
    .absoluteCenterWrapper p { /* Pushes 

    to edge of image */ margin-left: 101px; /* Width of image */ } .absoluteCenter { /* Specifies width of image to avoid overlap if image changes */ width: 101px; /* Width of image */ } /* Sizing - resizes down to avoid cutting off */ .absoluteCenter { max-height: 100%; max-width: 100%; } /* Making it "pretty" */ .absoluteCenterWrapper { margin: 1em; padding: 0.001em; /* <- Hack to contain margins */ outline: 1px solid red; } .absoluteCenterWrapper p { margin-top: 1em; margin-bottom: 1em; padding-left: 1em;}

    Paragraph goes here.

    Paragraph goes here.

    Paragraph goes here.

    Paragraph goes here.

    Paragraph goes here.

提交回复
热议问题