Center Oversized Image in Div

前端 未结 12 1634
予麋鹿
予麋鹿 2020-11-27 08:52

I have been trying to sort out how to center an oversized image within a div using css only.

We are using a fluid layout, so the width of the image containers varies

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 09:48

    Building on @yunzen's great answer:

    I'm guessing many people searching for this topic are trying use a large image as a "hero" background image, for example on a homepage. In this case, they would often want text to appear over the image and to have it scale down well on mobile devices.

    Here is the perfect CSS for such a background image (use it on the tag):

    /* Set left edge of inner element to 50% of the parent element */
    margin-left: 50%;
    
    /* Move to the left by 50% of own width */
    transform: translateX(-50%);
    
    /* Scale image...(101% - instead of 100% - avoids possible 1px white border on left of image due to rounding error */
    width: 101%;
    
    /* ...but don't scale it too small on mobile devices - adjust this as needed */
    min-width: 1086px;
    
    /* allow content below image to appear on top of image */
    position: absolute;
    z-index: -1;
    
    /* OPTIONAL - try with/without based on your needs */
    top: 0;
    
    /* OPTIONAL - use if your outer element containing the img has "text-align: center" */
    left: 0;
    

提交回复
热议问题