El ancho del div interno 100% del div principal excede los límites

My inner #div_mainPanel is 100% width, but if you look at the right-bottom corner it's over the parent div. I have tried removing width: 100 from the inner div and the width problem is solved, but not height.

Why does it display outside of the parent div if I have set width to 100% and margin/padding is set to 0px?

Gracias por adelantado

#div_mainContainer {
  width: 500px;
  height: 300px;
  background-color: #f8f8f8;
  border: 1px solid red;
  margin: 0px;
  padding: 0px;
}

#div_mainPanel {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 1px solid yellow;
}
<div id="div_mainContainer">
  <div id="div_mainPanel"></div>
</div>

preguntado el 08 de noviembre de 11 a las 16:11

Thanks everyone for your time! -

5 Respuestas

This is correct behaviour. The inner div is set to 100% width of the parent, but this does not include the border on it, so it is 100% + 2px.

To prevent the inner div being displayed outside the bounds of the parent, add box-sizing: border-box to both the parent and the child:

#div_mainContainer {
  width: 500px;
  height: 300px;
  background-color: #f8f8f8;
  border: 1px solid red;
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

#div_mainPanel {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 1px solid yellow;
  box-sizing: border-box;
}
<div id="div_mainContainer">
  <div id="div_mainPanel"></div>
</div>

respondido 06 nov., 17:11

Borders count for sizing calculations. Your inner div picks up 100% of the height/width of the parent, so it becomes 500x300, but then adds 2px all around for the border, so it's really 502x302 and leaks over the parent's border on the right/bottom edges.

respondido 08 nov., 11:20

One minor observation: If it adds 2px border all around, size becomes 504x304. :) - Ganesh Jadhav

There is now a much better way to solve this problem: use border-box sizing for your CSS:

http://paulirish.com/2012/box-sizing-border-box-ftw/

AHORA 100% will be a much more natural way to set sizes of child elements.

Respondido 06 Jul 13, 01:07

thats because the border attribute goes over the 100%... same as the padding value.

thats why its 2px out.

respondido 08 nov., 11:20

The border property is not calculated in the width of the box either. So your box is actually being calculated as 100% + 2px for the border. For the width, just remove the width: 100% because a division (block-level element) will already expand to fill the width of the container automatically, better than a 100% width can do (because it will consider padding, border, and margin).

If you're always using an exact height on the parent container, why not just use an exact height of 498px on the child, which will calculate to a total height of 500px for the child.

respondido 08 nov., 11:20

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.