6

# 6The CSS box model

## Relative & absolute positioning

There is one final point that I will address with this website and this is the use of absolute positioning of HTML elements. All the elements used so far have used static positioning, that is to say their positions were determined by other elements (generally the order in which they occur in the HTML file). Static positioning has been used because this is the default setting for HTML elements.

Absolute elements have fixed positions, to illustrate this we will add a date to the top-right of the main area box.

Create a new date class in the CSS file

style.css
.date{
position: absolute;
top: 10px;
right: 30px;
}
 Code 6.19   style.css (absolute positioning) a

The position: absolute property ensures that the element to which this class is applied will be (in this case) located 10 px down from the top margin of the parent element and 30 px in from the right margin of the parent element (that is to say the last character in the element will be 30 px from the right margin).

Now it’s a golden rule that for absolute positioning to work, the parent element must be set to relative positioning (and all ours are by default set to static); so for this to work properly, the parent element (in this case the .main-area <div>) must be formally set to relative positioning, add the following:

style.css
.main-area {
position: relative;
. . .

 Code 6.20   style.css (relative positioning) a

Now, we add the HTML (let’s put it in after the first <h1> element):

index.html
    <body>
<div class="container">
<div class="main-area">
<h1>This is the main heading</h1>

<p class="date">Jan 03<sup>rd</sup>, 2017</p>

<h2>This is a second heading</h2>

 Code 6.21   index.html (absolute positioning) a
• I’ve used the <sup>...</sup> element in the date paragraph, this is another text forming element, it makes the “rd” of the date superscript characters, i.e. it shifts them up a bit to make it look right.

And here is the result:

Remember the rule:

 For absolute positioning to work, the parent elementmust be set to relative positioning.

In the website proper I will set all elements to relative positioning by adding it to the asterisk selector:

* {
box-sizing: border-box;
position: relative;
margin: 0;
padding: 0;
}