简体   繁体   English

如何在不影响宽度/高度的情况下更改 DIV 填充?

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

我有一个 div,我想为其指定一个固定的宽度和高度,还有一个可以在不减少原始 DIV 宽度/高度或增加它的情况下更改的填充,是否有 CSS 技巧,或者使用填充的替代方法?

Declare this in your CSS and you should be good:在你的 CSS 中声明这个,你应该很好:

* { 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
     box-sizing: border-box; 
}

This solution can be implemented without using additional wrappers.该解决方案可以在不使用额外包装器的情况下实现。

This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.这将强制浏览器根据 div 的“外部”宽度计算宽度,这意味着将从宽度中减去填充。

Solution is to wrap your padded div , with fixed width outer div解决方案是用固定宽度的外部 div包裹你的填充div

HTML HTML

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

        <!-- your content -->

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

CSS 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.听起来您正在寻找模拟 IE6 盒模型。 You could use the CSS 3 property box-sizing: border-box to achieve this.您可以使用 CSS 3 属性box-sizing: border-box来实现这一点。 This is supported by IE8, but for Firefox you would need to use -moz-box-sizing and for Safari/Chrome, use -webkit-box-sizing . IE8 支持此功能,但对于 Firefox,您需要使用-moz-box-sizing ,对于 Safari/Chrome,请使用-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. IE6 已经计算出错误的高度,所以你在那个浏览器中很好,但我不确定 IE7,我认为它会在 quirks 模式下计算相同的高度。

try this trick试试这个技巧

div{
 -webkit-box-sizing: border-box; 
 -moz-box-sizing: border-box;    
 box-sizing: border-box;      
}

this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.这将强制浏览器根据 div 的“外部”宽度计算宽度,这意味着将从宽度中减去填充。

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 .为了在跨浏览器中获得一致的结果,您通常会在div内添加另一个div并且没有明确的 width 和margin The margin will simulate padding for the outer div. margin将模拟外部 div 的padding

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM