DEV Community

anderu
anderu

Posted on • Updated on

The use of 'margin: auto' on flex children and 'position: relative, absolute, fixed'

  • We can position a child item in the container with the use of
.parent-element {
    display: flex;
    justify-content: center;
    align-items: center;
}

// Another option
.parent-element {
    display: flex;
}

.child-element{
    margin: auto;
}
Enter fullscreen mode Exit fullscreen mode
  • But the use of margin on flex children element can done more than just center the item, you can refer to the image below to check where you can position your item:

flex children element positioning with margin


Image showcase the use of absolute and relative position

  • Position absolute and relative is useful when you want to allocation an element in the parent element

  • As example show on the image above, to make the 'Exclusive' word locate at the top left, we can code as below

.parent-element {
    position: relative;
}

.child-element {
    position: absolute;
    top: 0;
    left: 0;
} 
Enter fullscreen mode Exit fullscreen mode
  • If we did not use the position: relative on parent-element the the 'Exclusive' word will allocate on the top left of the window. There are top, right,bottom, left method to use to position the absolute element around the parent-element.

chat button fixed on the bottom right of the website

  • If we want to position an element on a fixed location in the window like the chat button on the picture above even we scroll up and down then we can use
.element {
    position: fixed;
    bottom: 0;
    right: 0;
}
Enter fullscreen mode Exit fullscreen mode
  • This code will 'fixed' the element on the bottom right of the window all the time.

There are extra space below the image

  • Fun Fact: There are extra space below the image because Images created with img tag by default has display: inline property. To fix this, simply code
.image {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

This is today sharing, please feel free to share your thoughts, ideas, or corrections if I have presented any inaccurate information.

Eat, sleep, code, repeat!
Andrew Tan

Top comments (0)