July 7, 2015

CSS Positioning and floating elements


Positioning and Floating are the properties mainly used in css to layout the webpage. Let's see the different types of positioning available in css and discuss them with their usage.

There mainly four types of positioning

  • Static.
  • Absolute.
  • Relative.
  • Fixed.
Let's discuss one by one with their code snippet.

html

<div id="positioning">Helloo</div>

Static Positioning:
This is the default position of the element. If two elements are inline, then both of them stacked horizontally one after the other. In the same way if two elements are block then both the elements stacked one after the other vertically. Know more about Inline and Block elements.

Absolute Positioning

#positioning {
      position: absolute;
      top: 10px;
      left: 10px;
}
This way positioning take its position in the webpage with respect to (0,0) co-ordinates which mean from top left corner and it's position is fixed it doesn't adjust itself with respect to screen resolution. Actually it;s not flexible way of positioning the elements.

Relative Positioning

#positioning {
      position: relative;
      top: 10px;
      left: 10px;
}
The element take it's position with respect to its current position and more 10px from top and 10px from left. Many developers use relative positioning over absolute because it's more flexible way of doing things done.

Fixed Positioning

#positioning {
      position: fixed;
      top: 10px;
      left: 10px;
}
This element takes it's position with respect to the screen. When ever you give an element with fixed position then when you scroll down your webpage the element with fixed position also scrolls down along with the webpage. This type of positioning generally used for menu bars or nav bars to make to visible for the whole web page when user scrolls down.

Now, you have seen about positioning. I strongly recommend you to play around with these things as they are most confusing things in the CSS for the beginners. Now, let's move on for Floating the elements.

html

<div id="floating">This is a floating element</div>

css

#floating {
    float: left;
}
#floating {
    float: right;
}
#floating {
    float: inherit;
}
#floating {
    float: none;
}

You can learn more about floats here. You will find an awesome article about floating elements in the given link.

No comments: