Do you like my tutorials?

Then consider supporting me on Ko-fi

Talking about Css, Html and Javascript.

Recently a lot of sites feature a full screen background image. Full screen background images can be used to give some sort of liquid effect to fixed layouts, or just to show full screen images in some special occurrences, such as Christmas or the launch of a new service.

This is what you’ll get: demo.

Before you continue reading this post, I have to warn you the title is misleading: you won’t center any background image. You are going to achieve this effect by using an image in div with a a low z-index.

During this example we’ll use a this photo by horlo.

HTML

As said, it’s an image inside a div, so let’s create them:






     

The div has an id called triquiback while the image has triquibackimg. It should be the first thing you add after body opening.

CSS

z-index and positions will be defined with CSS this way:





     


     

Notice the z-index of #triquiback and its overflow: being an <img /%gt; image and not a background, I had to set the overflow to hidden to prevent unwanted scrollbars. Also, the left and top positions are set to zero to override body margins and paddings.

Both the div and the image have fixed position to allow to easily place them with left and top.

jQuery

jQuery will allow us to resize the image as we want.





     
     AUTO RESIZE BACKGROUND IMAGE
     
     


     

At line 6 I import jQuery library using Google as CDN.

The code is filled with alerts which will guide you through the demo, obviously you can remove them from your project.

Line 9: Function to be executed once the document is ready

Line 10: Function to be executed once the "background" image is loaded

Lines 11-12: Getting document area with and height

Lines 14-15: Getting "background" image width and height

Line 17: Determining image ratio as width/height

Line 19: Setting image width equal to document width

Line 20: Adjusting image height according to new image width and image ratio

Lines 22-23: Resizing the image

Line 24: Checking if the new image height is shorter than document height. In this case we need to resize the image again

Line 25: Setting image height equal to document height

Line 26: Adjusting image width according to new image height and image ratio

Lines 28-29: Resizing the image. At this time, we need to horizontally center the image

Line 30: Calculating half of the difference between new image width and document width

Line 32: Adding a style to image to move it by such difference to the right

And that's it. You can check the demo here. In case of positive feedback, I'll show you how to resize image on the fly when the browser is resized, and add an overlay to image.

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.