In this tutorial, I will show you how to make an element that is too big for some screens visible when it does fit, but not trigger scrolling when it doesn’t. I’ll also show you how to center it. Essentially, we can make an element in a website behave just like the background of the <body> element. It took me a while to figure out the bugs with this, but eventually I was able to solve the problem.
Let’s clarify our objectives.
1. The element must be visible (not cut off) when the browser is big enough in size to see it.
2. It should not trigger the ability to scroll when the window is too small, but when other elements allow you to scroll, will still scroll with them (not fixed.)
3. We should be able to specify a minimum size for the important aspects of the element, so that if the window is even smaller than this size, you can still scroll to those important parts.
4. The element should be centered on the page.
Still confused about what this means? Check out this demo of the solution which will help explain what we are trying to do.
The html:
1 2 3 |
<div id="box"> <div id="element"></div> </div> |
Nothing too fancy, basically just a box or container div around the div with your element. In my case, the div IS the element. The magic, now, is in the CSS.
The CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
html, body { height:100%; } body { margin:0px; padding:0px; min-width:1000px; /*Set the width you want to be able to scroll to here*/ } #element { height:100%; position:relative; /*This section centers your element*/ left:50%; margin-left:-800px; /*Half the width of the image*/ z-index:-9999; /*This part puts it behind everything, not needed if you aren't making a background*/ background:url(image.jpg) no-repeat; } #box { height:100%; min-height:700px; /*Set the height you want to be able to scroll to here*/ overflow:hidden; /*Needed due to centering with margins*/ } |
That’s basically all you have to do. You can put anything you want within the #element div, and it should still behave how it is supposed to. I use it on a website for cycling through divs like a slideshow using jquery cycle. It took me a while to figure out this solution, but I think it works pretty well, so let me know in the comments if you have any trouble with it.
Keep in mind, this isn’t going to work quite the same with any other positioning. You are going to run into problems with just about anything else. If you didn’t care about centering, you would probably be fine leaving your positioning as static but that is probably the best you can hope for. Check out the working demo.