skip to Main Content

How can I change the width in child to put it inside parent div. It should be internal to padding. In this case top and left are fine but right is not proper.

https://jsbin.com/tuhohuvoxa/edit?html,css,output

.parent {
  padding:20px;
  border: 0.1em solid;
  height:200px;
}

.child{
  position:absolute;
  border:0.1em solid;
  height:10px;
  width:100%;
}

2

Answers


  1. You just need to add this position to your parent & child element :

    .parent {
      position: relative;
    }
    
    .child {
      left: 0;
    }
    

    Then the child with position absolute will adapt to the parent.

    Login or Signup to reply.
  2. If you do not need the child to be absolute, simply removing the position:absolute from the .child class will make the width match the parent without overflow.

    If you really need the .child class to be absolute you can update the .child and .parentclasses as follows:

    .parent {
      padding:20px;
      border: 0.1em solid;
      height:200px;
      position:relative;
    }
    
    .child {
        position: absolute;
        border: 0.1em solid;
        height: 10px;
        left: 0;
        right: 0;
        margin-left: 20px;
        margin-right: 20px;
    }
    

    Setting position:relative on the parent will ensure the child is relative to the parent. Setting left and right to 0 will ensure the child matches the parent width, and adding the margin-left and margin-right will ensure the child is inset from the parent.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search