Reputation: 33571
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:
Thanks.
Upvotes: 6
Views: 7370
Reputation: 52659
block-sizing: border-box
didn't work for my particular problem but there is another way for those coming back to this question:
use position: absolute
along with right:0
(or bottom for vertical constraints) to constrain the child to the parent. The parent element should have position: relative
and it is forced to fit perfectly.
Upvotes: 0
Reputation: 723518
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.
Upvotes: 9
Reputation: 1532
Not a perfect solution but it worked
Remove left and right padding padding:20px 0;
and set text-indent:20px;
on input
http://jsbin.com/aleta4/2/edit
Upvotes: 0
Reputation: 303198
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.
Upvotes: 3
Reputation: 360592
Unfortunately, no. Width calculations are done before any padding/margins are taken into account, so a child with width 100% will be 100% of the parent's, after which margins/padding are added, so you'll end up with something over 100%.
You can fake the effect by putting on a border of the same color as the background. This would work, since you've got a solid background for the child to span over.
Upvotes: 0