When an element overlaps its container for no reason (usually when 100% width or height are set)

The situation is you have a container (say a div), with some width and height something simple like this

.cont{
  width: 200px;
  height: 100px;
  border: solid; border-width: 1px; border-color:#ccc;
  padding:5px;
}

 

And then, you put a child element inside

.child{
  width: 100%;
  height: 100%;
}

 

The HTML

<div class="cont">
  <input type="text" class="child">
</div>

 

The result

Why is this happening? The width and height of the child element is 100%, PLUS the border and padding.

To avoid the situation, add box-sizing: border-box to the child element, so that the 100% will include borders and padding, like this:

.child{
  width: 100%;
  height: 100%;
  box-sizing: border-box  
}

 

And your child element will beautifully be were you need it to be:

Published by

Nelson Muskus

Full Stack developer

Leave a Reply

Your email address will not be published.