Search code examples
cssbackground-image

100% width & height background-image not working


I want the background-image to cover the whole available space without getting squashed.
Actually I thought that's whats background-size is for, but I guess I am doing something wrong because its not working, please help me.

HTML

<div class="myDiv">
    <p class="paragraph">Lorem Ipsum</div>
</div>

CSS

body {
    background-color: black;
}

.myDiv {
    color: white;
    background: url('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png') no-repeat center center fixed; 
    background-size: cover;
}

FIDDLE
http://jsfiddle.net/V7KSb/


Solution

  • Just make body and html 100% height and likewise for the div

    body, html{
        height:100%;
        padding:0;
        margin:0;
    }
    .myDiv {
        color: white;
        background: url('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png') no-repeat center center fixed; 
        height:100%;
        padding: 20px;
        box-sizing: border-box;
    }
    

    See fiddle: http://jsfiddle.net/V7KSb/5/

    Updated: given myDiv some padding and used box-sizing: border-box; to ensure it doesn't go bigger than 100%.