Search code examples
cssbackgroundbackground-attachmentbackground-size

Attach an image to the top of the page, no scroll for img, in the body element


I have the following problem. I think, there is a quick way to do it, but right now I cannot find the way to solve it.

So, I have an image and I want it to be as a background image ONLY on the top of the page in the <body> element. Currently it is moving to the bottom of the page if I scroll down.

I have the folllowing code:

body {
    color: #d0d0d0;
    font-family: Verdana, Tahoma, sans-serif; 
    font-size: 12pt;
    font-weight: 400; 
    font-style: normal;
    line-height: 1.5; 
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    margin: 0;
    z-index: 0;
    background:url(../img/main-bg-top.png) no-repeat top center;
    background-attachment: fixed;
    background-size: cover;
}

Solution

  • Well you could create another class and insert it before of all your content, something like this: Jsfiddle

    body {
        color: #d0d0d0;
        font-family: Verdana, Tahoma, sans-serif; 
        font-size: 12pt;
        font-weight: 400; 
        font-style: normal;
        line-height: 1.5; 
        text-rendering: optimizeLegibility;
        -webkit-font-smoothing: antialiased;
        margin: 0;
        z-index: 0;
        background:#000;
    }
    .top-image{height:0;}
    .top-image img{max-width: 100%;}
    .container{height:900px; }
    

    html:

    <div class="top-image">
        <img src="http://www.wormzweb.com/images/photoalbum/album_28/nature_2118.jpg">
    </div>
    <div class="container">
        <p>random text.</p>
    </div>
    

    This was a quick sketch, workaround with the best way for you and the proper way to write this code if you wanna.