mauzilla
mauzilla

Reputation: 3592

use margin or position relative to position elements

I have always used margin to move a floating div to the correct position in a parent div (say the logo div within a header div). This has always worked but that meant you have to play with the individual height of the elements else it will affect the remainder of the layout downwards.

I found another method today and that is to make the logo div position: relative; and then use example top: 20px; to move the element around, and this does not appear to affect the layout.

I don't want to adapt to this without knowing that there may be other implications, so can anyone point out common flaws in either of the above methods or possibly suggest a better solution?

  // Sample HTML
  <div id='header'>
        <div id='logo'>
              LOGO GOES HERE
        </div>      
  </div>

  // Sample CSS
  #header {
        height: 100px;
  }

  // Version 1
  #logo {
        float: left;
        margin-top: 20px;
  }

  // Version 2
  #logo {
        float: left;
        position: relative;
        top: 20px;
  } 

Upvotes: 3

Views: 19623

Answers (2)

Allan Kimmer Jensen
Allan Kimmer Jensen

Reputation: 4389

From Mozilla developer:

relative Lay out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned). The effect of position:relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.

I hope this answers your question.

Sometimes it might be the right thing to use, other times not. It really depends on your layout, if you want to make a responsive design, it might be better to have the margin there.

In your case you have a fixed height on the header, so you can use relative. I think it is a more common practice to use margin. I am only aware on issues concerning position: fixed on mobile devices.

You can learn more about CSS and positioning here.

Upvotes: 2

Saeed
Saeed

Reputation: 3775

In postion absolute and fix when u use top or bottom or right or left,you must not use float, you must for its parent use this style

postion:relative;

best regards

Upvotes: 1

Related Questions