Best way to set width + padding

I could faff around and do some tests to work this out, but thought it’d be easier to get opinions. If setting

width:100%;
padding:5px 10px; 

This will push the 100% over. What’s the best way to keep the width and have the padding?

width:100%;
max-width: 100%;
padding: 5px 10px;

would that retain the width and padding?

If the element is a block element simply remove the width and that width will then be auto and expand to fill the available space automatically including any padding and borders.

If you are talking about widths other than 100% then use the border-box model and all padding and borders will be included inside the specified width.

.test {
	-moz-box-sizing:border-box;
	-webkit-box-sizing:border-box;
	box-sizing:border-box;
	width:300px;
	padding:50px;
}

That will work back to IE8,

These days I set all my elements by default to the border-box method as it is more natural and about the only thing that IE got right from the start.

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

More info

You could mess around with calc and subtract the padding and borders from the width but the border-box model s much easier and has greater support.

BTW setting width and max-width with the same units is nonsense because only one can be true so just use width if you want a fixed width.

1 Like

That’s what I was doing - playing around and subtracting the padding from the box - guessing game when there’s a mixture of % and px.

Will have a play around with above. Cheers OB

One also has to CONSIDER WHEN to add ‘WIDTH:100%’.

If you are dealing with a block element, or at least one with display:block; assuming it’s not floated, AP’ed, etc ) it automatically has width:100%; So the best solution in that case is to set ONLY the padding and not the width; I believe, Paul mentioned this.
CLARIFICATION: by default, a block element has width:auto; which means it will take that it’s CALCULATED width will be 100% of its parent element(and it does not include the parent’s padding)-the padding of the element itself. for all appearances…it looks as if the element+ its padding=100%;

Tables ( or display:table;) will also automatically included the padding in the calculated width.

So that leaves , mainly, floats and inline-blocks. For those, you could use -box-sizing, or move the padding out to the container.

hope that helps

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.