s.k.paul
s.k.paul

Reputation: 7291

Parent div is not expanding as child div grows

I have an inner div in an outer div.

When I am setting top: SomeValue for innerdiv, it overlaps outer div.

#div1{
    position: relative;
    top: 10px;
    left: 20px;
    width: 50%;
    background: green;
}

#div2{      
    position: relative;
    top:5px;
    left: 20px;
    width: 80%;
    background: red; 
}

Here is my jsfiddle

How to overcome it?

Upvotes: 0

Views: 253

Answers (3)

Tanner
Tanner

Reputation: 22733

Relative Positioning:

A relative positioned element is positioned relative to its normal position.

http://www.w3schools.com/css/css_positioning.asp

You're using relative positioning on div2, so it is ignoring the fact that it's a nested div and moving it away from it's normal position.

I've updated the fiddle with a workaround:

http://jsfiddle.net/P6dbe/2/

The fiddle removes the relative position of div2 and adds padding to div1, with the below css:

#div1
    { 
      position: relative; 
      padding-top: 5px; 
      padding-bottom: 5px; 
      padding-left: 20px; 
      top: 10px; 
      left: 20px; 
      width: 50% ; 
      background: green; 
    }

#div2
    { 
      width: 80%;  
      background: red; 
    }

Upvotes: 0

guymid
guymid

Reputation: 1206

You are positioning div2 partially outside of div1. If you want to constrain div2 within div1 you need to set overflow:hidden on div1.

#div1
    { position: relative; top: 10px; left: 20px; 
      width: 50% ; background: green; overflow:hidden;}

Upvotes: 0

Jabran Saeed
Jabran Saeed

Reputation: 6158

You cannot use Top attribute for this. As it will ignore it's parent's boundaries.

Use padding-top instead

{ position: relative; padding-top:5px; left: 20px;  width: 80%;  background: red; }

Upvotes: 1

Related Questions