March 14, 2012

img maximized in the background inside a div

Question by danielovich

I have been fiddling around with this for some time now, but I still don’t understand how it should be done.

I would like the image to be maximized (100%/100%) in the background of the itemtemplate div, but right now it just makes it fit inside the div which is 250px/250px.

<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
    <img style="-ms-grid-row-span: 2;" src="#" data-win-bind="src: backgroundImage; alt: title" />
    <div class="item-overlay">
        <h4 class="item-title" data-win-bind="textContent: title"></h4>
        <h6 class="item-subtitle win-type-ellipsis" data-win-bind="textContent: subtitle">
        </h6>
    </div>
</div>

Any ideas ? thx.

Answer by Starx

I am not familiar with the attributes you are using. But, in order to use an image for the background. There are couple of ways.

  1. If it is <body> or <table> you can also define them by using doing something like this

    <body background="link/to/image.jpg">
    
  2. But the global way, which every element supports would be to define them using CSS

    <div style="background-image: url("link/to/image")">...</div>
    

Now, coming to the image part

Whenever you are using a background image,

  • It is never going to re-size to fit the container. Unless you use CSS3.

    /* CSS3 Snippet to resize a background */
    div
    {
        background-image:url("link/to/image");
        -moz-background-size:80px 60px;
        background-size:80px 60px;
        background-repeat:no-repeat;
    } 
    
  • If the container is big, it will start repeating itself to fill the area. Which can be controlled to repeat or not repeat. Like

    div { 
        background-image: url("link/to/image");
        background-repeat: no-repeat; /* similary repeat-x and repeat-y */
    }
    

However, what you are trying to use in using a <img /> to act as a background, which is semantically wrong and I do not recommend it.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!