Sir
Sir

Reputation: 8277

Position absolute not inside parent

I have a problem with my CSS regarding div positions.

I have a parent div which is set to position:relative and a child div set to position:absolute

But for some reason the child div is displaying below and outside the borders of the parent div...

This is my CSS:

.big{
    position:relative;
    width:40%;
    border:1px solid black;
    display:inline-block;
}

.small{
    position:absolute;
    width:75px;
    height:75px;
    border:1px solid green;
}

The HTML:

<div class="big">        
    <p align="center">Test</p>
    <div class="small"></div>        
</div>
<div class="big">
    <p align="center">Test</p>
    <div class="small"></div>    
</div>

I have provided a JSFiddle to show you it in action:

http://jsfiddle.net/j6VLc/1/

How do i fix it to make the child div be inside the parent div whilst using position:absolute for it?

Upvotes: 6

Views: 22411

Answers (2)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60587

You can't do this using position: absolute as it removes the element from the normal document flow. position: relative on the parent will change where the position: absolute is positioned relative to, but it will not expand to contain the position: absolute. You will need to set a fixed height or using position: relative instead.

Note, if using position: relative in your example, you will need to add a margin-bottom equal to the value of top to make it expand to contain the position: relative.

.big {
    position: relative;
    width: 40%;
    border: 1px solid black;
    display: inline-block;
}

.small {
    position: relative;
    width: 75px;
    height: 75px;
    border: 1px solid green;
    top: 50px;
    left: 40px;
    margin-bottom: 50px;
    margin-right: 40px;
}
<div class="big">
    <p align="center">Test</p>
    <div class="small"></div>
</div>
<div class="big">
     <p align="center">Test</p>
    <div class="small"></div>
</div>

Upvotes: 7

user15479861
user15479861

Reputation: 21

As you have given a height of 75px to the child div and inside the parent div you have also given <p> which is a block element so the <p> tag is making its space and after that your child div is appearing....Make the div height of parent element larger than child and style the <p> tag to display: inline;

.big {
    position: relative;
    width: 40%;
    height: 100px;
    border: 1px solid black;
    display: inline-block;
}

.small {
    position: absolute;
    width: 75px;
    height: 75px;
    border: 1px solid green;
}

p {
  display: inline;
}

Hope this will get you to what you want.

Upvotes: 2

Related Questions