DIV Absolute respect padding DIV father

Asked

Viewed 1,279 times

0

I need to put a div with the property position = absolute. However, the div father has a padding and the width: 100% of div son does not respect this padding.

Would the only way out be to define the width with the javascript?

I put an example here:

.master {
  background-color: red;
  width: 200px;
  height: 300px;
  padding: 10px;
  position: relative;
}

.child {
  width: 100%;
  height: 30px;
  background-color: yellow;
  position: absolute;
}
<div class="master">
  <div class="child">
  
  </div>
</div>

  • I don’t understand if you want to respect the padding and reduce the width of the yellow, or if you just support the yellow. Absolute positioning does not respect ancestral padding.

  • I want to respect the padding

  • The padding changes the size of the element, so it is expected that the child element, configured with width: 100%, also get 220px wide. Take out the position: absolute, as @bfavaretto said and will have an element with 200px.

  • If you want a div to occupy the entire width of the father, respecting the paddings, why then use position: absolute? Using div in your pattern already does this. Just take the properties width and position from there.

  • Ali was just an example, I need position: absolute because that div yellow will float over the remaining content

1 answer

1


If I understand correctly, this is what you want.

*,*:before,*:after{
    box-sizing: border-box;
}

.pai{
    position: relative;
    width: 300px;
    height: 300px;
    background: black;
    padding: 10px;
}

.filho{
width: calc(100% - 10px);
height: 50px;
background: red;
position: absolute;
left: 5px;
}
<div class="pai">
        <div class="filho">
            
        </div>
    </div>

  • In fact it’s almost that, but the width of div son would have to have the 100% of the div father less the padding of div father.

  • @Robertofagundes I updated

  • Thank you, it worked out the way I’d hoped

  • It is worth remembering that calc is an experienced technology and should be used very carefully. It is possible that some browsers do not support or have a different behavior than expected.

  • In fact, calc(100% - 20px);, because it has padding on both sides, and remove the left of the son.

  • @Dudaskank Yes, there was only one example

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.