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

A Smarter Way To Learn HTML & CSS(2015)

64
Layout:
a modern header part 1

The box diagram we’ve been working with shows the header section scaled a little narrower than the body section, with some whitespace at the top.

When the page displays, there’s a small amount of whitespace between the top edge of the window and the top of the header. And there’s a small amount of whitespace also on both sides of the header. This happens automatically if you don’t override it.

A header with whitespace all around it is acceptable, but a more modern design would have the header on a color block that is flush with the top of the window and stretches all the way across the window from edge to edge. The box diagram would look like this.

Let’s make one of these modern headers.

We start by making the header stretch from edge to edge. And we create the color block by giving it a background-color of dark crimson.

div#header {
width: 100%
background-color: #990000;
}

This is the HTML that creates the div.

<div id="header">

[The contents of the div will go here.]

</div>

By specifying a width of 100%, we’ve asked the browser to stretch the div from edge-to-edge, but the browser isn’t cooperating fully. It’s still leaving a little whitespace on the left and right edges.

So we need to force the issue:

div#header {
width: 100%
position: absolute;
left: 0;
background-color: #990000;
}

By specifying position: absolute, we override whatever the browser thinks we mean by width: 100% and explicitly tell it where we want the left edge to start. By specifying left: 0, we say, “Start it 0 pixels in from the left edge of the window.” In other words, eliminate all whitespace. Happily, without any additional instructions, the browser eliminates all whitespace on the right edge as well.

But, thanks to the browser’s tendency to surround a div with whitespace, we still have a gap above the header. How do we solve this? You can probably guess.

div#header {
width: 100%
position: absolute;
top: 0;
left: 0;
background-color: #990000;
}

Now we’ve told the browser to start the div 0 pixels from the top of the window. The gap disappears.

So do we see a color block at the top of the browser? No. If you open the page in a browser, the color block isn’t anywhere to be found.

In the next chapter I’ll deal with this.

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