简体   繁体   中英

How to force position absolute with 100% width to fit into parent div with padding?

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.

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

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;
}

一旦你使用绝对位置,div 就不会在它的父 div 中。相反,你可以使用相对位置并给它width:inherit这将继承父 div 的宽度

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%;
}

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 eg padding: 0 10px ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM