Search code examples
javascriptjquerycssmobile-devices

Fixed div as background on mobile devices


I want to use a div as a background for a website.

If I use position:fixed and set the width & size to the viewport size the design breaks on mobile devices/tablets as they do not support the fixed position.

What's the best way to set a div as a static background, so that it works on mobile devices too?


Solution

  • I'm not entirely sure how you intend to use the background, but I created a loose way to do this here. The tacky background is applied to a div the size of the screen, and it will not move (as long as you're careful with what you put inside it). However, the same effect could be done just by direct styles on the body - I'm not sure what exactly you need the div for, so I can't guarantee this technique will work for your use case.

    How it Works

    With disclaimers out of the way, here are a few details on how it works. All content will have to appear within two divs: one outer one that has the background, and an inner one to hold all of the content. The outer one is set to the size of the page and can have the background applied to it. The inner one then is set to the size of the parent, and all overflow is set to scroll. Since the outer one has no scrollbar, any interior content that exceeds the size of the background tag will cause a scrollbar to appear as though it were on the whole page, not just on a section of it. In effect, this then recreates what the body is on the average web page within the "content" div.

    If you have any specific question on the styles, let me know and I'll flesh out the mechanics in more detail.

    With jQuery

    I suppose there's still one remaining option: use similar style rules, but absent the ability to nest everything within the background, instead prepend it, and change it's position whenever the user scrolls, like so.

    Then, just inject this code:

    <style>
    #bg {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0px;
      background-image: url(http://cdn6.staztic.com/cdn/logos/comsanzenpattern-2.png:w48h48);
      margin: 0px;
      padding: 0px;
      overflow: hidden;
    }
    </style>
    
    <script>
    $("body").prepend("<div id='bg'></div>");
    $(document).on("scroll", function () {
      $("#bg").css("top", $(document).scrollTop())
              .css("left", $(document).scrollLeft());
    });
    </script>
    

    modifying the style rules for the background div accordingly, and you should be good. It will not have a good framerate since this will always appear after the scroll paint, but you're running low on options if you have so little control over the rest of the document structure and style.