Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to use an entire image as a website background using CSS and still cater to different screen sizes? (like about.me)

Currently I'm using this:

HTML:

<div id="container">
  <img src="x.jpg" id="bg" />
  <div id="content">
   <h1>Welcome to my website.</h1>
   <p>Boo!</p>
  </div>
</div>

CSS:

#bg{
position:absolute;
top:0;
left:0;
height:100%;
z-index:10;
}

#container{
/* max values provided due to the max size of the image available with me(1200x800) */
max-width:1200px;
max-height:800px;
}

#content{
position:absolute;
top:10px;
left:100px;
z-index:100;
}

The advantage here is that I'm not using any Javascript at all. But then, the absolute-ly positioned elements become a nightmare when viewed on different screens.

Currently the solution I have is write and position these elements according to different screen sizes (for example, 1024x768 would have the id content's top value as 10px whereas 1280x800 will have something like top:25px; and so on..) and store them as a separate css file so I can load the appropriate CSS during page load. I feel this is time-consuming and probably in-efficient too. Using percentage values is an option I haven't explored yet. If you know of an elegant solution, or how the big guys at about.me do it, it would help.

Thank You.

like image 409
dsignr Avatar asked Dec 31 '11 19:12

dsignr


People also ask

How do I fit a full background image in CSS?

There are four different syntaxes you can use with this property: the keyword syntax ("auto", "cover" and "contain"), the one-value syntax (sets the width of the image (height becomes "auto"), the two-value syntax (first value: width of the image, second value: height), and the multiple background syntax (separated ...

How do I make an image fit my website background?

When you work with background images, you may want an image to stretch to fit the page despite the wide range of devices and screen sizes. The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover.

What CSS property is use to set the image as a background of the whole web page?

The background-image CSS property sets one or more background images on an element.

Is it better to put images in HTML or CSS?

Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.


1 Answers

Have you tried using background-image on the body with one of the background-size values? You could use cover or perhaps 100% 100% depending on your needs.

Demo: http://jsfiddle.net/ThinkingStiff/UBaN6/

body {
    background-image: url('http://thinkingstiff.com/images/matt.jpg');  
    background-size: cover;  
    background-repeat: no-repeat;
}
like image 102
ThinkingStiff Avatar answered Nov 01 '22 05:11

ThinkingStiff