Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe I have a solution that achieves what you're wanting:</p> <p><strong>A background image (specifically a page background) offset by a number of pixels with respect to the center.</strong></p> <p>This works using only HTML &amp; CSS - no javascript required.</p> <hr> <h2>Update</h2> <p><strong>This can now be easily achieved using <code>background-position</code> and <code>calc</code> as a CSS unit.</strong></p> <p>The following CSS will achieve the same outcome as the previous solution (see "Original Solution" below):</p> <pre><code>#background-container { width: 100%; background-image: url("background-image.png"); background-position: calc(50% - 50px) 50%; background-repeat: no-repeat; } </code></pre> <p><strong>Note:</strong> Don't use this method if you require support for legacy versions of IE.</p> <hr> <h2>Original Solution</h2> <pre><code>#background-container { width: 100%; left: -100px; /* this must be TWICE the required offset distance*/ padding-right: 100px; /* must be the same amount as above */ background-image: url("background-image.png"); background-position: center; background-repeat: no-repeat; } </code></pre> <p>What this does is moves the the entire container horizontally by the amount specified (in this case to the left 100px). Because the background image is centered relative to the container it moves to the left with the container.</p> <p>The padding fixes the 100px of blank space that would appear to the right of the container as a result of the move. Background images show through padding). Because browsers use the border-box value instead of the default content-box value to calculate background sizing and positioning, the background image is effectively moved back to the right 50px - half the distance of the padding. (Thanks to ErikE for clarification).</p> <p>So your offset/padding must be twice the required offset distance.</p> <p>I have prepared a sample page for you here: <a href="http://www.indieweb.co.nz/testing/background-offset-center.html" rel="noreferrer">http://www.indieweb.co.nz/testing/background-offset-center.html</a></p> <p>Have a play with resizing the window. You will see that the purple and blue background image (laid over a deeper background image marking the center of the page) remains exactly 50px (half the offset/padding distance) to the left of the page center.</p> <hr>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload