Skip to content

Categories:

Quick Tip – Make a Full Screen Image Background With a Line of CSS

Full screen image backgrounds are a must if you are creating a portfolio or a photography website. This usually involves using a jQuery plugin, which will properly resize the image with the browser window, and do the necessary calculations so that the image covers the entire width and height of the page.

But did you know that if you are ready to sacrifice support for IE8 and below, you can have that kick ass effect only with a line of CSS? Here is how..

The background-size property

With background-size, you can tell an element how large its background image must be. Like this:

#elem
    background:url('kermit.jpg') center center no-repeat;
    background-size:100px 150px;

But even more convenient, this property supports two magical values: contain and cover:

  • Contain resizes the background image so that it fits entirely in the element;
  • Cover is more interesting – it makes so that the element’s background is entirely taken up by the image. The image is resized to the smallest size that allows it to cover the element entirely (see the illustration below). This is also the property we will be using for our full screen background.
Background-size Cover vs Contain

Background-size Cover vs Contain

So all we have to do, is to set the image we want displayed full screen as a background to the html element:

html
	/* This image will be displayed fullscreen */
	background:url('background.jpg') no-repeat center center;

	/* Ensure the html element always takes up the full height of the browser window */
	min-height:100%;

	/* The Magic */
	background-size:cover;


body
	/* Workaround for some mobile browsers */
	min-height:100%;

And now you have your image displayed full screen! It will change its dimensions as you resize the window or change the orientation of mobile devices. It works on all recent desktop and mobile browsers (without IE8 and below as mentioned above).

A big thanks to Zanthia for his wonderful image.

|Did you know that you can set an image as a full screen background to your page with only a line of CSS?}

Read more : Quick Tip – Make a Full Screen Image Background With a Line of CSS

Posted in Uncategorized.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.