Mahesha999
Mahesha999

Reputation: 24731

Filling image in div

I want to create a basic layout for webpage with divs and want to set images for their background. Since I have smaller images I want to stretch them to fill in the divs.

There are many ways to do that. But I tried following:

</html>
<head>
    <style>
       img#bg {  
         top:0;
         left:0; 
         width:100%;
         height:100%;
       } 
   <style>
<head>
<body>
  <img src="body.jpg" alt="background image" id="bg" />
  <div id="content"> </div>
<body>
</html>

This worked. Then I tried to make use of it in layout.

    <div id="hmenu" style="zindex=1;height:80px;background-color:#007980"></div>        
    <div id="content"  >
        <img src="body.jpg" alt="background image" id="bg" />
    </div>

This also worked. But when I tried to set image this way for a div with float:left or CSS width set, it did not worked:

  <div id="header" style="zindex=1;height:300px;width:100%"></div>
    <div id="hmenu" style="zindex=1;height:80px;background-color:#007980"></div>        
    <div id="content" style="float:right" >
        <img src="body.jpg" alt="background image" id="bg" />
    </div>

This doesnt work. In last HTML notice float:right. I will like to stick to this method, not any jQuery method or others and also will like to know what is wrong here and what should be done to get the desired result with CSS modifications as I am learning this.

Upvotes: 0

Views: 286

Answers (3)

Nerbiz
Nerbiz

Reputation: 134

background-size: cover;

Is a nice solution, but I'm not sure about the browser support, because it's CSS3.

I made a fiddle, is this what you were looking for? http://jsfiddle.net/NQY6B/5/

By the way, change "zindex" to "z-index".

EDIT: I've updated the fiddle with text content in the div

Upvotes: 0

Jamie Hutber
Jamie Hutber

Reputation: 28076

In order for height: 100%, Top:0 etc to work you need to have a position applied to the element.

You don't as per the example code given. Give more code and i can help more. But from what you have given this is your problem.

Upvotes: 0

Andy
Andy

Reputation: 14575

Seems like you want a background image

A good explanation can be found here

Basically you can make a div have a background using CSS and not having to put an tag inside, this is almost always preferable.

Example code for you could be:

body {
   background-image: url('body.jpg');
   background-size: cover;
}

Upvotes: 2

Related Questions