HTML and CSS Reference
Fixing Elements Inside the Browser Window
When you set an element's position property to fixed , the offsets tell the browser where to position the element
in relation to the browser window. When you scroll the page, the element remains where you placed it, but other
content scrolls behind. If you don't set a right or left offset, the element remains in the same position horizontally
as it would be normally. How this works is best seen through an example.
eXerCISe: CreatING a FIXeD heaDer aND MeNU
in this exercise, you'll make the header and horizontal navigation menu of a page remain onscreen while
the rest of the page is scrolled. Use as your starting point fixed_begin.html and styles/fixed_begin.css in the
ch11 folder. The finished files are fixed_end.html and styles/fixed_end.css.
1. Add the position property to the #header style rule, and set its value to fixed .
background-image: url(../images/yachts banner.jpg);
save the style sheet, load the page into a browser, and start scrolling. As Figure 11-3
shows, the header isn't displayed full width, and it's pushed away from the top, but it
remains in the same position with the other content scrolling behind.
Figure 11-3. The header needs adjusting, but it remains in a fixed position while the other content scrolls
scroll back to the top of the page, and use the browser's developer tools to inspect
the nav unordered list, which is used as the horizontal menu. As Figure 11-4 shows,
the gap between the header and the top of the browser window is identical to the
15px top margin of the unordered list.