Make elements hang outside your main page container, without triggering scrollbars if the window is too narrow

We all know how to make layouts that have a horizontally centered element of a fixed with:

	#mainContainer {
		position: relative;
		width: 1000px;
		margin: auto;
	}

and that give you this:
Centered element with margin: auto

So what if you want to add a logo or something that sticks off the side of that container? Easy, just give it an absolute position.

	#mainContainer {
		position: relative;
		width: 1000px;
		margin: auto;
	}
		#hangingChad {
			position: absolute;
			top: 20px;
			right: -50px;
		}

Which gives you this:
Centered with margin:auto, and element hanging off.

But what happens when a user has their browser window a little too small i.e. smaller than your main container + the amount that the hanging element sticks out (times 2 because that extra width has to show on both sides)? This:

Arrrgghh Scrollbars

So how do you fix it? You make a fake body element, which is 100% width, with overflow hidden, to contain everything else.

#fakeBody {
	position: relative;
	width: 100%;
	min-width: 1000px;
	overflow: hidden;
}
	#mainContainer {
		position: relative;
		width: 1000px;
		margin: auto;
	}
		#hangingChad {
			position: absolute;
			top: 20px;
			right: -50px;
		}
	<div id="fakeBody">
		<div id="mainContainer">
			<img src="whatever.jpg" id="hangingChad" />
		</div>
	</div>

Basically, this makes the 1000 wide mainContainer center itself, and show it’s element that hangs outside, but when we make the window smaller the fakeBody element matches the window width no matter what, and it’s overflow: hidden style makes it cut off the extra hanging out bit.

The only remaining problem is making sure the browser does show scrollbars if we make it smaller than the mainContent element. To fix that, we add a min-width:1000px; style to the fakeBody, so it matches the window until it gets to 1000px, at which point it sticks at 1000px and the browser makes scrollbars.

This entry was posted in HTML/CSS and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Make elements hang outside your main page container, without triggering scrollbars if the window is too narrow

  1. Thomas says:

    Nice solution. Thanks!

  2. I love your Blog, it’s nice when you can tell somebody actuallly puts effort into a blog, and gives the blogs value.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>