Search code examples
htmlcssimagecenter

How to create center image in div?


i have image with resolution 1000px*1000px,

this my html :

<style> 
 .test{
  width: 400px;
  height: 400px;
  }
</style>

<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>

if original image full body, i want when on div only visible the face. i do not know how to make it.

Anyone can help me? Thanks in advance


Solution

  • USE THIS HACK.

    1. Let all the <img> tag have a src value to the same image (e.g. transparent-image.png). Using an image editor, set the image opacity to zero, thus making the image completely transparent. This transparent image should be made 1px by 1px in size.

    2. Then set an inline style on all the <img> tag with background-image set to an image of your choice. Understand that the src value (transparent-image.png i.e image with opacity set to zero) as set on the <img> will not obstruct visibility of its own background-image as defined in the inline style. This is because the image opacity is set to zero.

    3. Lastly, create a css rule on the <img> tag and set the background-position to center vertical and center horizontal. For example;

      .test img { background-position: center center; }

    Below is a template putting together all I have explained.

    The HTML

    <div class="test"> 
        <img src="transparent-image.png" style="background-image:url(image1.jpg)" /> 
    </div>
    <div class="test"> 
        <img src="transparent-image.png" style="background-image:url(image2.jpg)" /> 
    </div>
    <div class="test"> 
        <img src="transparent-image.png" style="background-image:url(image3.jpg)" /> 
    </div>
    

    The CSS

    .test {
        width: 400px;
        height: 400px;
    }
    
    .test img {
        background-position: center center; /* you can adjust this with values. Eg 50% 50% */
        background-repeat: no-repeat;
        background-size: cover;
    }
    

    Goodluck!