Keep an Image Always Centered Regardless of Browser Size

前端 未结 3 770
無奈伤痛
無奈伤痛 2020-12-17 01:01

I am wondering if it is possible to keep an img inside a div always centered regardless of the browser size? By being centered I mean that the left

3条回答
  •  萌比男神i
    2020-12-17 01:47

    Try this: http://jsfiddle.net/9tRZG/1/

    #wrapper {
        max-width: 200px; /* max-width doesn't behave correctly in legacy IE */
        margin: 0 auto;
    }
    #wrapper img{
        width:100%;       /* the image will now scale down as its parent gets smaller */
    }
    ​
    

    To have the edges cropped, you can do this: http://jsfiddle.net/9tRZG/2/

    #wrapper {
        max-width: 600px; /* so this will scale down when the screen resizes */
        margin: 0 auto;
        overflow:hidden;  /* so that the children are cropped */
        border:solid 1px #000; /* you can remove this, I'm only using it to demonstrate the bounding box */
    }
    
    #wrapper .slides_container{
        width:600px;            /* static width here */
        position:relative;      /* so we can position it relative to its parent */
        left:50%;               /* centering the box */
        margin-left:-300px;     /* centering the box */
    }
    #wrapper img{
        display:block;          /* this allows us to use the centering margin trick */
        margin: 2px auto;       /* the top/bottom margin isn't necessary here, but the left/right is */
    }
    

提交回复
热议问题