Lesson 8 – CSS3 Positioning

CSS3 allows you to position any HTML5 element anywhere on your webpage. There are actually three types of positioning properties in CSS3. Similarly, you can use four different values for a position property in CSS3.

  • Left: moves an element to the left using a negative value.
  • Right: moves element to the right using a positive value.
  • Down: pushes element down using a positive value.
  • Up: moves element up using a negative value.

Relative positioning

Relative-position property changes the position of element relevant to its natural position or where it normally appears. For example, “right: 50px” adds 50px to the right of the element.

Here is a sample code for you to understand the concept.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 Paddings</title>
    <style>
        div {
            position: relative;
            left: 100px;
            top: 20px;
            color: orangered;
        }
    </style>
</head>
<body>
    
This div has relative positioning.
</body> </html>

The following is how the browser will render the code.

Absolute Positioning

The element with position-absolute property is positioned absolute according to its parent element. In other words, it is positioned relative to the top left corner of your screen at specified coordinates.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 Paddings</title>
    <style>
        div {
            position: absolute;
            left: 100px;
            top: 20px;
            color: orangered;
        }
    </style>
</head>
<body>
    
This div has absolute positioning.
</body> </html>

Here is how the browser will render the above style rules.

Fixed Positioning

It is also possible to fix an element to any specific place or spot on your screen. Therefore, the element will always be visible no matter how much you scroll.

Here is an example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 Positioning</title>
    <style>
        div {
            position: fixed;
            left: 100px;
            top: 100px;
            color: orangered;
            border: 2px dashed black;
            width: 250px;
        }
    </style>
</head>
<body>
    
This div has fixed positioning.
</body> </html>

The final output of the above code is as under.

In the next lecture, we will study box sizing in CSS3.