Search code examples
jqueryhtmlbackground-imagecover

Mimic the css background cover img property in html


Thanks all for your responses. However, I haven't found any good answer to my question. So let me be more clear.

PURPOSE

As I'm working on SEO, I need to include images as html elements and mimic all the css attributes.

What I currently have

I added images within the css in order to expand/stretch and always center them in the middle of a div.

.page-electricite-generale .one {
    background: url('assets/images/elec/XXXX.jpg') 50% 50% no-repeat;
    background-size: cover;
}

Here is a jsfidle example

As you can see, the center of the image is always centered, without any crop/distortion inside the div.

What I need

I want to integrate images as html element and mimic the previous jsfidle.

Here is the jsfidle with an html image

Thanks


Solution

  • You have several possible solutions:

    1. Combine tag and background image

    This one is easiest. You put image in your markup like you would normally but hide it and use background-image on parent element. All modern browsers will download your image only once and cache it so you don't need to worry about performance. Just mind your image has correct path depending on file.

    Example:

    <div class="img-holder">
      <img class="hidden" src="/assets/images/elec/XXXX.jpg" />
    </div>
    
    
    .hidden {
        border: 0;
        clip: rect(0 0 0 0);
        height: 1px;
        margin: -1px;
        overflow: hidden;
        padding: 0;
        position: absolute;
        width: 1px;
    }
    
    .img-holder {
        background: url(assets/images/elec/XXXX.jpg) 50% 50% no-repeat;
        background-size: cover;
        // define your container width and height
    }
    

    2. CSS hacks

    Check out this article: https://css-tricks.com/perfect-full-page-background-image/

    There are several techniques listed there. This one worked for me:

    .parent {
      position: absolute; 
      top: -50%; 
      left: -50%; 
      width: 200%; 
      height: 200%;
    }
    
    .parent img {
      position: absolute; 
      top: 0; 
      left: 0; 
      right: 0; 
      bottom: 0; 
      margin: auto; 
      min-width: 50%;
      min-height: 50%;
    }
    

    3. Object-fit property

    img { object-fit: cover; }
    

    This is new property that is basically background-size version for images in markup. Unfortunately, browser support is not there yet.

    Resources:

    https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit http://caniuse.com/#feat=object-fit