How to change a DIV padding without affecting the width/height ?

Viewed 131535

I have a div that I want to specify a FIXED width and height for, and also a padding which can be changed without decreasing the original DIV width/height or increasing it, is there a CSS trick for that, or an alternative using padding?

6 Answers

Solution is to wrap your padded div, with fixed width outer div

HTML

<div class="outer">
    <div class="inner">

        <!-- your content -->

    </div><!-- end .inner -->
</div><!-- end .outer -->

CSS

.outer, .inner {
    display: block;
}

.outer {
    /* specify fixed width */
    width: 300px;
    padding: 0;
}

.inner {
    /* specify padding, can be changed while remaining fixed width of .outer */
    padding: 5px;
}

Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing and for Safari/Chrome, use -webkit-box-sizing.

IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.

To achieve a consistent result cross browser, you would usually add another div inside the div and give that no explicit width, and a margin. The margin will simulate padding for the outer div.

if border box doesnt work you can try adding a negative margin with your padding to the side that's getting expanded. So if your container is getting pushed to the right you could do this.

.classname{
  padding: 8px;
  margin-right: -8px;
}
Related