Brian Johnson Brian Johnson - 11 months ago 46
CSS Question

How to make a "Fixed" element Scrollable

I know this sounds somewhat counterintuitive, but let me explain what I am trying to do.

I have a large element that serves as the background. It does not resize. It is often larger than the screen it is viewed on. Most of the content of this element (it's just an image) is near the center. Let's say that the only NECESSARY information is in the middle 800px, and the whole thing is 1600px wide.

Why is it wider than necessary? Because it fades pleasingly into the rest of the background and adds to the design of the site.

So I made the element fixed and used a standard trick to center it. It works perfectly on a large monitor. It stays centered, if some of it is a little too big, it doesn't allow you to scroll over in order to see what is basically nothing. I like that.

But if the screen is too small, you can't see it all. You can't just set the min-width or min-height of the page because when you go to scroll, the background image stays in place, because it is fixed.

If there was a way to have a fixed element actually move with everything else when the page is scrolled, that would work perfectly, because I could specify the min-width to the size of the required elements of the image. That would work very well.

Otherwise, another solution would be to use some other form of positioning that allows for the prevention of being able to scroll to see the whole thing. Then, again, I could just set the whole with a minimum width, which would allow me to set exactly how much of the content is scrollable.

Is any of this possible? I feel like I am missing something simple. Ideally I would not have to resize any images, serve up multiple css sheets, or use any elaborate javascript or anything like that. Thanks for the help!

Answer Source

I have finally solved this problem after a ton of experimentation and the solution turned out to be basic CSS, which is awesome.

I go into great detail illustrating this solution at my blog. Alternatively, here is the working demo.


 <div id="box">
  <div id="element"></div>


<style type="text/css">
html, body {
body {
 min-width:1000px; /*Set the width you want to be able to scroll to here*/
#element {
 position:relative; /*This section centers your element*/
 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 {
 min-height:700px; /*Set the height you want to be able to scroll to here*/
 overflow:hidden; /*Needed due to centering with margins*/