简体   繁体   中英

CSS: Get a center-positioned fluid image background

This has been annoying me now for a few hours as I keep fiddling around with the code and don't seem to be getting anywhere at all.

I really like the way that this website has a fluid image background:

Here

I have downloaded the code and am not currently trying to make a slideshow, but instead a single image background that when you play around with the size of your browser expands and contracts the same way as in the website.

If i take the code that they use in their CSS and apply it to my own image I keep getting this instead.

https://jsfiddle.net/9cpz4gua/

body{
        background-image:url(https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg?width=960);
    background-repeat:no-repeat;
        width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    color: transparent;
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: none;
    opacity: 0;
    z-index: 0;

        }

Could someone please advise me what to do in order to get my background image to expand and contract about the center as the website does?

Here is my answer, it may not be the easiest or the most complete but it give a very beautiful looking result that answers your question

Basically, you create a new div directly under your body and style it this way:

.bgimg {
    z-index: 1;
    background: url(http://dondev.ovh/light_abstract.jpg);
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
}

See it in action

This is a css only answer, you can use JavaScript alongside for better result.

Regards

If all you want is to have your image always fill the page, just remove some things from your own style to achieve the "cover" effect.

Try this:

body{
    background-image:url(https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg?width=960);
    background-repeat:no-repeat;
    color: transparent;
    background-size: cover;
    opacity: 0;
    z-index: 0;
}

https://jsfiddle.net/9cpz4gua/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM