开发者

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 m开发者_C百科ove it 400 pixels to right... how can it be done


This can't currently be done using classical background-position notation.

You would have to use JavaScript to calculate the element's width and set the position accordingly, or give the image some transparent space to the left to push it to the right. This might be the easiest 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.


It could be done with background-clip and background-origin, but that is in the future: http://www.css3.info/preview/background-origin-and-background-clip/

A wrapper DIV or JavaScript should do it.


I would try to manipulate with <div> with positioning and z-index


It may be simpler with Javascript.

Pseudocode:
    Read the width of the enclosing element
    Compute its center
    Offset the center by desired amount of pixels
    Set this new value as the position of the background image
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜