[Solved – 10 Answers] CSS 100% height with padding/margin
With HTML/CSS how to make an element that has a width and/or height that is 100% of it’s parent element and still has proper padding or margins?
The parent element is 200px tall and we specify 100% height with 5px padding we expect to get a 190px high element with 5px “border” on all sides, nicely centered in the parent element.
The challenge is then to get the black box to show up with a 25 pixel padding on all edges without the page growing big enough to require scrollbars.
The display:block is the default display value for the div. The container has to be the right type; position attribute is fixed, relative, or absolute.
<div class="stretchedToMargin"> Hello, world </div>
There is a new property in CSS3 that you can use to change the way the box model calculates width/height, it’s called box-sizing.
By setting this property with the value “border-box” it makes whichever element you apply it to not stretch when you add a padding or border. If you define something with 100px width, and 10px padding, it will still be 100px wide.
Just make sure you don’t forget the space between the values and the operator (eg (100%-5px) that will break the syntax.
Another solution: You can use percentage units for margins as well as sizes.
For example:
css code
.fullWidthPlusMargin { width: 98%; margin: 1%; }
[ad type=”banner”]
Here’s an example where the child – given padding and a border – uses absolute positioning to fill the parent 100%. The parent uses relative positioning in order to provide a point of reference for the child’s position while remaining in the normal flow – the next element “more-content” is not affected:
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.