6
votes

I have 2 divs, an outer div which is a parent and a child div. The outer div is position relatives with padding 20px for left and right while the child is position absolute with 100% widthg. How can I force the child which is position absolute to be within the parent, ie respecting the padding 20px (inside parent and within the 20px padding)

I've done the example here: http://www.bootply.com/nyGZzTVY8v

I've read about box-sizing but I still don't understand how to implement it correctly. Tried putting it on the box1 class and nothing happen, tried putting on the box2 class and nothing happen also.

thanks in advance.

Additional Note: It has to be responsive ie I do not know the size of the parent div thus the 100% for the child div.

5
Nope, not 2 divs in your example. 1 div, 1 p and 1 a. - Lee Kowalkowski

5 Answers

5
votes

If it has to be responsive, you could add the the padding as a margin and then use calc for the width:

.box2 {
    position: absolute;
    width: calc(100% - 40px);
    left: 0px;
    padding: 50px 0;
    margin: 0 20px;
    colour: #000;
    background: #fff;
    border: solid thin #06F;
}
8
votes

Just set left: 20px; and right: 20px; and remove width: 100%

Live Demo

.box2 {
    position: absolute;
    padding: 50px 0;
    color: #000;
    background: #fff;
    left: 20px;
    right: 20px;
    border: solid thin #06F;
}

or add left: 20px; and the calc function width: calc( 100% - 40px )

.box2 {
position: absolute;
width: calc( 100% - 40px );
padding: 50px 0;
color: #000;
background: #fff;
left: 20px;
border: solid thin #06F;
}

live Demo

0
votes

Once you use position absolute the div wont be in its parent div.instead you can use position relative with and give it width:inherit this will inherit the width of the parent div

0
votes

This works perfect, try it out. The parent div should have a relative position and the child div could have an absolute position like you want.

.box1 {
    width: 50%;
    margin: 10px;
    position:relative;
}
.box2 {
    display: block;
    position: absolute;
    width: 100%;
}
0
votes

I went through this problem recently and found the solution via setting left & right of child container resolve problem.

If you want child container to have same parent padding e.g padding: 0 10px i.e left & right. Then we need to set left & right of child container with the same value as parent padding.

.box1 {
  position: relative;
  padding: 0 10px;
}
.box2 {
  position: absolute;
  left: 10px;
  right: 10px;
}

To see code-pen click here