Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre a header image regardless of page size

My webpage has a header image that always remains at the top of the window. When the window is maximised the header image is centred, but when viewing in a small window (or a smart-phone browser) the header is set to the left of the window, and the right side cropped. Because the header div is wider than the page content, the horizontal scroll-bar appears when the window is smaller than the header, not the page.

I would like the header image to be centered on the page at all times, with both left and right sides being cropped if the window is smaller than header. Also the horizontal scroll-bar to only be turned on if window width is less than page width.

This image might explain it more clearly:

imagehttp://postimage.org/image/49ne3k3o/

My code so far:

CSS:

#headerwrap {
    position: relative;
    width: 998px;
    height: 100px;
    margin: 0 auto;
    pointer-events: none;
}
#header{
    position: fixed;
    top: 0;
    width: 998px;
    margin: 0;
    background: url('../images/top.png') no-repeat;
    height:100px;
    z-index: 1;
    pointer-events: none;
}

and HTML implementation:

<div id="headerwrap"\>
<div id="header">
</div>
</div>

(the page is 690px wide, the header is 998px)

Any help would be much appreciated.

like image 832
James Avatar asked Jan 19 '23 09:01

James


1 Answers

You need to set left: 50% on the header element that has position: fixed, and then apply a negative margin of half that element's width to center it.

#header {
  height: 100px;
  width: 998px;
  position: fixed;
  top: 0;
  left: 50%;
  margin-left: -499px;
  background: url('../images/top.png') no-repeat;
}

Here's a quick fiddle: http://jsfiddle.net/blineberry/w8P2S/

You don't really need a wrapper for this.

like image 104
Brent Avatar answered Jan 21 '23 23:01

Brent