Layout: a modern header part 4 - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

67
Layout:
a modern header part 4

In the last chapter you learned how to force the browser to position a div precisely where you want it. The header that we created using this approach appears in that position when the page first displays. Then if the user scrolls the page, the header scrolls with all the other content. But you can tell a browser to leave a div where you put it, to not scroll it when the page scrolls. For example, you might want the header to stay visible at the top of the browser window as everything below it scrolls. Here’s the code. (I’m omitting all the header styling that I covered in the last chapter.)

div#header {
position: fixed;
top: 0;
left: 0;
}

position: fixed tells the browser to keep the div immobilized as everything else on the page scrolls. This makes the div’s position within the window permanent. As you learned in the last chapter, top: 0 and left: 0 tell the browser to place the header flush against the top of the window and flush against the left side of the window.

If you were to write this…

div#ad-box {
postion: fixed;
top: 150px;
left: 50px;
}

…the div with the id “ad-box” would be permanently positioned 150 pixels from the top of the window and 50 pixels in from the left side of the window.

You can also specify a position some distance (or no distance) in from the right side of the window. The following code positions the ad box flush against the top of the window and 10 pixels in from the right.

div#ad-box {
postion: fixed;
top: 0;
right: 10px;
}

Alternatively, you can specify a position some distance (or no distance) up from the bottom of the window.

div#footer {
position: fixed;
bottom: 0;
left: 0;
}

I’ve coded the positions in pixels, because that’s easier for you to understand. But, as you know, percentages are preferable, so…

div#ad-box {
postion: fixed;
top: 0;
right: 2%;
}

In your CSS file change the absolutely-positioned div to fixed position. Save the file and display the page. Try scrolling down from the top. (Don’t be surprised to see the header cover up some content. We’ll deal with this in the next chapter.)

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-67-1.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/67.html