简体   繁体   中英

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

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.

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.

我会尝试使用<div>进行定位和z-index操作

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM