6
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
.date{ position: absolute; top: 10px; right: 30px; }
Code 6.7.1 style.css (absolute positioning) |
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:
Now, we add the HTML (let’s put it in after the first <h1> element):
<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.7.3 index.html (absolute positioning) |
And here is the result:
Remember the rule:
For absolute positioning to work, the parent element |
|
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; }