HTML background image offset by x pixels from the center

后端 未结 9 1327

I\'d like to put an image as the background of a webpage but have it offset by some number of pixels with respect to the center.

How can I do this?

I want:

相关标签:
9条回答
  • 2020-12-23 09:22

    the units need to be the same, so when specifying pixels for the x-position, the y-position needs to be also in pixels.

    example:

    background-position: 25% 50%;
    

    EDIT: I just re-read your query and the only way to do that is either knowing the absolute position (assuming the outer elements aren't dynamic/flexible), or in case you don't know the position, maybe use javascript to set its position.

    0 讨论(0)
  • 2020-12-23 09:25

    Using background-position: center; is the same as background-position: 50% 50%;.

    So you can use calc to do some simple math in CSS as a replacement for any length value, for example:

    background-position: calc(50% - 50px) 50%;
    

    Will center the background image, but shift it 50 pixels to the left.

    0 讨论(0)
  • 2020-12-23 09:26

    There's no obvious CSS answer. You would either need to use JavaScript to calculate values or do something tricky. You can try keeping the background-position:25% center and adding position:relative;left:-50px or margin-left:-50px but those might not work depending on how you are using the DOM element.

    0 讨论(0)
  • 2020-12-23 09:26

    The only method I've found for this is to have the background inside another div, then use javascript to reposition ...

    <style>
        body {
            width: 100%;
            overflow: hidden;
            }
        #bg {
            position: absolute;
            background: url(images/background.jpg) center top;
            }
    </style>
    
    <script>
        function recenter(){
            var $pos = $('#content').offset().left;
            $('#bg').css('left',$pos-580);
        }
        recenter();
        $(window).resize(function(){ recenter(); });
    </script>
    
    <body>
        <div id="bg"></div>
        <div id="content">
            blah
        </div>
    </body>
    
    0 讨论(0)
  • 2020-12-23 09:26

    My answer gotta be too late but somehow I've found another solution.

    padding-left: 100px; /* offset you need */
    padding-right: 100%;
    

    or

    padding-right: 100px;
    padding-left: 100%;
    

    The examples have the same effect.

    0 讨论(0)
  • 2020-12-23 09:38

    if you know the width of the image you can use this:

    background-position: (BgWidth - 50)px 0px;
    

    Note that you can't have it like that, i.e. you need to calculate (BgWidth - 50) and then write the number there.

    If you don't know the width you can use Javascript(with-or-without jQuery) and then use this:

    $(#ID).css('background-position', (BgWidth - 50)+'px 0px');
    
    0 讨论(0)
提交回复
热议问题