Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

I have an element within another element. The parent is of a certain size. I want the child to be the exact same size, but at the same time have a padding.

If I don't know the exact size of the parent, is there any way to get it to be the same size as the parent and have a padding?

problem:

http://jsbin.com/odemu3/edit

Thanks.

like image 864
Mark Avatar asked Dec 25 '10 22:12

Mark


2 Answers

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.

like image 79
BoltClock Avatar answered Mar 01 '23 14:03

BoltClock


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.

like image 22
Phrogz Avatar answered Mar 01 '23 16:03

Phrogz