arjit nair
arjit nair

Reputation: 51

HTML child wider than parent container

There is an outer div, and an inner div element. Sometimes I see that the inner div is wider than the outer div.

When does this happen? And how to overcome this issue?

<div id="outer">
  <div id="inner"></div>
</div>

Upvotes: 0

Views: 5719

Answers (2)

web-tiki
web-tiki

Reputation: 103780

According to comment the reason the inner element is wider than parent is caused by the margin/padding. This happens when you set

(width + padding + margin + border) of child > parent width

example

Workarounds :

  • For margin : You need to calculate (width + margin) of child =< parent width demo
  • For border and padding : You can use the box-sizing property to include padding and border in the width of the element demo (or use the same technique as margin)
  • For border, margin and padding : When you don't need to set a width on the inner element, remove it and the default behaviour for block elements will include margin, padding and border inside the parent demo

Upvotes: 6

Michael Chambers
Michael Chambers

Reputation: 74

<div id="outer">
  <div id="inner">Inner Text</div>
</div>
<style type="text/css">
  #inner,  #outer {
    box-sizing: border-box;
    width: 100%;
    border: solid 1px #000;
    padding: 1%;
  }
</style>

Upvotes: -1

Related Questions