How to change a DIV padding without affecting the width/height ?
To ensure padding doesn't alter the overall dimensions of your DIV, apply box-sizing: border-box;. This property includes padding and border in the element's total width and height:
The div remains a solid 300x200px on the outside, while the inside adjusts to accommodate the padding for your content.
Decoding the box-sizing property
The box-sizing: border-box; property tells the browser to count any border and padding within the width and height dimensions. The overall div size remains unchanged but padding gobbles up some interior content space.
The legacy browser lifeboat
Modern browsers have solid support for the box-sizing property. But if you find yourself strangled by legacy browser issues, the following prefixes are your lifebuoys:
Taking the scenic two-div route
While leveraging box-sizing is often the quickest route, there's another path. If you cannot, or prefer not, to change the box-sizing, establishing two divs can simulate the effect:
Ensure that .inner-div doesn't have a set width to let the padding spread across the full width, making it a worthy border-box opponent.
Nitty gritties and best practices
Designing for the moving screen
When you design responsively, every pixel is precious. With border-box, your DIV stands guard maintaining its size when padding goes through changes. This makes responsive designing less of a pain in the pixels.
Entertaining dynamic content guests
If your splendid div hosts dynamic content - dancing to user interactions - using border-box empowers you to modify padding with greater predictability since the outer dimensions mount a stubborn defence.
The border-box isn't always the hero
- Grid layouts: When dealing with CSS grid layouts, you may need to rethink the
border-boxstrategy as the grid system may require a finer manipulation of margins and padding. - Flex children:
border-boxcan sometimes clash withflex-growandflex-shrinkbehaviour in flexbox layouts, throwing you a curveball. Always proceed with testing!
The 'artwork' is the embodiment of DIV's content area which steadfastly stays the same size, while you conveniently adjust the padding, akin to tweaking the frame, but not encroaching the 'artwork'.
Was this article helpful?