开发者

center kitty? in jsFiddle! forcing background down

http://jsfiddle.net/TurtleWolf/P7xKm/

center kitty? in jsFiddle?

So I just want the background image 开发者_Python百科to not be below the rest of the html. This is a follow up to what Evan has already helped me with in the second link... So the image will re-size to any window, but now it's not acting as a background image... What's the best practices in html5 in for this situation?


Updated approach here: http://jsfiddle.net/irama/P7xKm/24/

Breaking it down...

You want to add a content layer:

<div id="content">
    <p>Hello kitty!</p>
</div>
<div id="container">
   <img src="http://placekitten.com/g/200/300" class="bg_image" />   
</div>

Then you want to take the 'container' element out of the document flow, so you can layer content on top:

.bg_image {
    width: 100%;
}

#container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
}

#content {
    position: relative;
    z-index: 2;
    background-color: #fff;
}

You can then either take or leave the JavaScript depending on whether you want the image vertically centred or not.


Given that the height of the image can change, you'll need JavaScript to recalculate the position when the window size changes.

Throw this in the JavaScript area in jsfiddle and set 'nowrap (body)':

$(function(){
    $('.bg_image').centerVertically();
    $(window).resize(function(){
        $('.bg_image').centerVertically();
    });
});

$.fn.centerVertically = function() {
    $(this).css('margin-top', $(window).height()/2 - $(this).height()/2);
};

See: http://jsfiddle.net/irama/P7xKm/22/

Or, for outside of jsfiddle, add this before your closing <body> tag:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script>

    $(function(){
        $('.bg_image').centerVertically();
        $(window).resize(function(){
            $('.bg_image').centerVertically();
        });
    });

    $.fn.centerVertically = function() {
        $(this).css('margin-top', $(window).height()/2 - $(this).height()/2);
    };

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜