Way to divide a single background image across multiple divs to create “windowed” effect?

后端 未结 3 2217
名媛妹妹
名媛妹妹 2021-02-19 19:38

I was wondering if there is an easy way to \"tile\" or \"window\" a single background image across multiple divs. I want to create a sort of punched out window look.

Ke

相关标签:
3条回答
  • 2021-02-19 20:06

    I came into something that's nearly a 100%. Feel free (anyone) to edit the answer.

    CSS

    #blocks {
        width:100%;
        height:100px;
    }
    .block {
        float: left;
        overflow: hidden;
        margin: 2%;
        width: 20%;
        height: 100%;
        background: transparent url(http://www.designmyprofile.com/images/graphics/backgrounds/background0172.jpg) no-repeat top left;
    }
    

    jQuery (JS)

    $(function () {
        var posX = 0;
        var posY = 0;
        var i = 0;
    
        $(".block").each(function (ind, el) {
            $(this).css("background-position", posX.toString() + "% " + posY.toString() + "%");
    
            posX += 20;
            i++;
    
            if (i == 4) {
                i = 0;
                posX = 0;
                posY += 25;
            }
        });
    });
    

    Demo (to be improved): http://jsfiddle.net/bzCNb/33/

    0 讨论(0)
  • 2021-02-19 20:12

    A CSS-only solution

    What you are describing is basically a table with a background image and white borders. A simple solution can be achieved by creating a table-like layout with CSS only.

    #background-container { 
        display:table;
        width:100%;
        border-collapse:collapse;
        box-sizing:border-box;
         /**/
        background: url(path-to-background-image) no-repeat center center;
        background-size: cover;
         /* Vendor specific hacks */
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
    }
    
    .blocks {
        display:table-row;
    }
    
    .block {
        display:table-cell;
        height:100px;
        border:10px solid #FFF;
    }
    

    See jsFiddle Demo

    0 讨论(0)
  • 2021-02-19 20:33

    Try putting the background on the blocks instead of the page with fixed attachment and alignment of left top. Unfortunately with this option if the page scrolls the background appears fixed.

    .block{
        float: left;
        overflow: hidden;
        margin: 2%;
        width: 20%;
        height: 100%;
        background-image: url(http://www.designmyprofile.com/images/graphics/backgrounds/background0172.jpg);
        background-repeat: no-repeat;
        background-position: left top;
        background-attachment: fixed;
    }
    

    http://jsfiddle.net/bzCNb/28/

    0 讨论(0)
提交回复
热议问题