Search code examples
csspositioncss-positionmargin

CSS Using position relative+absolute or negative margin


I want to put a small div (50x50) on the center of another div (200x200).

I got 2 ways to do it:

Using position absolute and relative

position:relative
position:absolute
top:75px;
left:75px;

or

Using negaive margin

margin:-125px 0 0 75px;

I would like to know which way is better and why...
I heard some people saying that position is not recommended.. is that true? why?

EDIT:
The divs are exmaples.
In reality I got image above another image (youtube preview image, and play button image above it).
The Images are inside accordion, and in ie6 closing the accordion/open it cause the absolute container to float above everything...


Solution

  • There is nothing wrong with using absolute and relative positioning, they have been fully supported for a long time. Of your two methods I would definitely go with the absolute and relative position one as the margin one is a little hacky.

    Personally I would use neither of your methods and instead put #small inside #big as it is a little more semantically correct (because #small is within #big).

    See on jsFiddle

    HTML

    <div id="con">
        <div id="big">
            <div id="small"></div>
        </div>
    </div>
    

    CSS

    #big {
        width:200px;
        height:200px;
        background:red;
        position:relative;
    }
    #small {
        position:absolute;
        width:50px;
        height:50px;
        margin-left:-25px;
        margin-top:-25px;
        left:50%;
        top:50%;
        background:blue;
    }