CSS Positions in a better way

the basic structure of a webpage is created using HTML.but the placement of the elements is decided as they are in the DOM tree. The only way to change a position of an element is by using the position property in the stylesheet. So let's discuss the position property in detail. there are a total of 4 types of positions

                  1.  Static 
                  2. Relative
                  3. Absolute
                  4. Fixed
  1. Static: This is the primary property that is default selected for the elements. if the margin is applied this will not work. these options let you follow the DOM structure
  1. Relative: The element is positioned according to the normal flow of the document, and then margin can be applied to of top, right, bottom, and left and the element will move from its initial position and the offsets will work relative to the parent position but the element will not affect other sibling elements.
  1. Absolute: the element is completely removed from the DOM tree so other sibling elements are affected by the absolute positioning of the element. it is placed relative to the initial containing block. Its final position is determined by the values of the top, right, bottom, and left of the initial block.
  1. Fixed: ever you watched an element that is sticky to the screen means if you swipe up or down the screen it still stays in the same place on the screen. That types of elements are known as Fixed types of elements. let's observe all of them in practice

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="box one">One</div>
<div class="box two">Two</div>
<div class="box three">Three</div>
<div class="box four">Four</div>
</body>
</html>

style for static position

.two {
    position:static;
    top: 100px;
    left: 100px;
    background: #ea00ff;
  }

static.PNG

style for relative position

styles.css

* {
    box-sizing: border-box;
  }

  .box {
    display: inline-block;
    width: 100px;
    height: 100px;
    background:#000000;
    color: #ffffff;
  }

  .two {
  #   position: relative;
    top: 100px;
    left: 100px;
    background: #ea00ff;
  }

relative.PNG

style for absolute style

.two {
    position: absolute;
    top: 100px;
    left: 100px;
    background: #ea00ff;
  }

absolute.PNG

fixed will stick the element at the end of a page and will stay in the same position although scrolling

Did you find this article valuable?

Support Dipanjan Sur by becoming a sponsor. Any amount is appreciated!