Search code examples
htmlcsspositioningbackground-imagemargin

HTML\CSS: background image positioning


i know we can position like this

background:url(../images/bg.jpg) top left;

but i want to do this

position the background to top center and move it 400 pixels to right... how can it be done


Solution

  • Edit: This was stubborn to do in IE, so I've added some extra information to make it work there as well.

    Edit2: Also used Microsoft's SuperPreview application to make this work in IE6. Tested in FF3.6 and IE8, as well as IE6 in SuperPreview.

    Use the following CSS to nest your object:

    body {
       margin:     0px;
       padding:    0px;
       text-align: center;
    }
    
    .parentDiv {
       margin:     0 auto;
       text-align: left;
       width:      2px; /* non-zero width */
    }
    
    .childDiv {
       position: relative;
       text-align: left;
       background-image: url("../images/bg.jpg");
       left:   399px !important; /* !important is not honored by IE6 */
       left:   600px;            /* overridden in all but IE6 */
       width:  300px;
       height: 300px;
    }
    

    You would have code similar to this (it's important to set DOCTYPE to strict):

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    ...
    <div class=parentDiv><div class=childDiv>Child Content</div></div>
    

    Change the value of width and height in childDiv based on your image.