Complete 2020 Web Development Bootcamp

Section 5 – Lessons 44 to 46

Lesson 44

In order to understand CSS positioning, you first have to understand the HTML rules for rendering elements on a web page.

The rules are:

  1. Content is everything –
    • “inline” elements only take up the width and height of the content;
    • “block” elements take up the full width of the web page and the height of the content.
  2. Order comes from the code –
    • elements are rendered on the web page in the order that they are written in the HTML code.
  3. Children sit on Parents –
    • So, for example an <h1> element sits on the <div> that contains it.

CSS Positioning

The four CSS position properties are:

  1. Static
  2. Relative
  3. Absolute
  4. Fixed

Static

All HTML elements are static by default.

Relative

The relative property allows an element to be positioned relative to how it would have been positioned had it been static.

An example of using the relative property in CSS to position an image element is:

img {
 position: relative;
 left: 30px;
}

As the image element is an inline element it if the HTML code is:

<body>
<h1>Heading</h1>
<p>Paragraph</p>
<img>

then the image element would have been positioned on the very left hand side of the web page. By using the CSS relative positioning property set out before, the image would be moved 30px from the left hand side of the web page.

The coordinate properties for the relative property are:

  • Top
  • Right
  • Bottom
  • Left

Lesson 45

Absolute

When you use the absolute positioning property in CSS, you are positioning the element relative to its parent. For example,

<body>
<div class="container">
  <h1 class="heading-1">Heading</h1>
</div>

In this example, the <div> is the parent element and the <h1> is the child element.

In order to use absolute positioning on the <h1> (child) element, you first have to assign relative positioning to the parent element. So,

.container {
 position: relative;
}

You can then position the child element, which in this case has been given the “heading-1” class, using absolute positioning.

.heading-1 {
 position: absolute;
 left: 50px;
}

Fixed

The fixed positioning element is used to fix an element in position so that it doesn’t move when the page is scrolled. For example, it can be used to fix a navigation bar to the top of the web page.

Lesson 46

“Text-align: center;” will center everything in a text element that doesn’t have a width. For example,

p {
 text-align: center;
}

However, if the text element has a specified width then “text-align: center;” won’t work to center the text. In that case, you have to center the text using “margin: 0 auto;”.

p {
 width: 200px;
 margin: 0 auto;
}