How can I make a child element be constrained by its parent’s width in CSS?

On supported browsers, set box-sizing to border-box (CSS3 only). This causes the browser to calculate the width of an element as content + padding + border + margin (as opposed to content-box in the CSS1/2 box model):

input {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

I believe inputs already have this setting by default, but this can also apply to any other child elements whose widths you want calculated like that.


Make the child element display:block (which will cause it to fill the width of the parent) and either give the parent padding or give the child a margin. Do not try to specify a width on the child element.

Tags:

Css