Sachin Jain
Sachin Jain

Reputation: 21842

CSS Margin and Absolute property

I want to use margin in my code, but I have some problems. Please look at:

<div id="outer">
<div id="inner1">
    Margin not coming from top (not absolute)
</div>

<div id="inner2">
    Div has absolue prop
</div>

And the CSS code is:

#outer {
    margin: 100px;
    background-color: green;
    height: 300px;
    widht: 400px;
}

#inner1 {
    margin: 10px;
    background-color: red;
}

#inner2 {
    position: absolute;
    margin: 20px;
    background-color: blue;
}

  1. I am not able to understand why setting position to absolute is restricting width of #inner2 div.

  2. Since #inner1 div does not have absolute property, it is not having margin from top. I can't understand this. Please explain.

Here is output: jsFiddle

Upvotes: 0

Views: 210

Answers (3)

abhinav pratap
abhinav pratap

Reputation: 623

Ques1: I am not able to understand why setting position to absolute is restricting width of inner2 div.

setting position to absolute of inner2 div, gets the width auto so as long as text. setting position to relative of inner2 div, gets the width of outer div.

So if you want absolute positioning, set also the width of inner2 div.

Ques2: Since inner1 div does not have absolute property, it is not having margin from top. I can't understand this. Please explain.

from the document flow, your inner div never know it is inside some other div (outer), setting border or position to absolute of outer div fix this.

fiddle http://jsfiddle.net/C7dE2/20/

Upvotes: 1

Usman
Usman

Reputation: 3278

setting position:absolute removes the element in question from the normal flow of the document structure. So unless you explicitly set a width it won't know how wide to be. you can explicitly set width if that is the effect you're after..

see this

absolute vs relative position width & height

Upvotes: 1

Josip Codes
Josip Codes

Reputation: 9521

You should use green div's padding-top property - #inner1 with margin-top set on high value only pushes the whole #outer further down!

Upvotes: 0

Related Questions