make something stretch to full width of browser inside of a fixed width element

Posted on

Just ran into this the other day and it saved me a ton of work. (I was prepared to have to end the fixed width div just to put this menu in and then start a new fixed width div below it. Using this method I did it all in CSS without having to change the page template)

Thanks (once again) to Chris Coyier’s CSS-Tricks for this.

So if you have an element, say a ul or an h2, that needs to stretch all the way across the screen, it will be naturally limited by the width of its parent element. Here is how to get around that: stick a nice wide pseudo-element that matches the background color both before and after it.

so it might be something like this:

section {
   width: 960px;
   margin: 0 auto;
}
h2 {
   position: relative;
   background: black; 
}
h2:before, h2:after {
   content: "";
   position: absolute;
   background: black;  /* Match the background */
   top: 0;
   bottom: 0;
   width: 9999px;   /* some huge width */
} 
h2:before {
   right: 100%; 
}
h2:after {
   left: 100%;
}

And then to make sure it doesn’t create some ugly horizontal scrollbars, add this while you’re at it:

html, body {
    overflow-x: hidden;
}
Posted in Wordpress Tips, Tricks and Reusable Bits of Code.