【问题标题】:Padding causes horizontal scroll - it increases the width填充导致水平滚动 - 它增加了宽度
【发布时间】:2014-03-04 12:01:26
【问题描述】:

请看这段代码:

<html>
<head>
<style type="text/css">
html, body{
width:100%;
height:100%;
margin:0px;
}

#header{
width:100%;
height:100px;
position:fixed;
display:inline-block;
background-color:red;
padding:0 10px 10px 10px;
}
</style>
</head>
<body>
    <div id="header">
         <div id="header-container">
         </div>
    </div>
</body>
</html>

这里是 demoheader 必须有 100% 的宽度和从左、右和底部的 10px 填充。请看这张图

这是 firebug 对#header 的布局。如您所见,图像中没有正确的填充,因为 10px 填充已添加到 #header 宽度(您可以对其进行测试)。如何在不增加宽度的情况下为#header 设置 100% 宽度和为左、右和下设置 10px 填充?

【问题讨论】:

    标签: html css width padding


    【解决方案1】:

    试试这个

     * , *:before, *:after{ 
         box-sizing:border-box; 
         -moz-box-sizing:border-box; 
         -webkit-box-sizing:border-box; 
         -ms-box-sizing:border-box;
       }
    

     #header{
     width:100%;
     height:100px;
     position:fixed;
     display:inline-block;
     background-color:red;
     padding:0 10px 10px 10px;
     box-sizing:border-box;  /** add this **/
     -moz-box-sizing:border-box; /** add this **/
     -webkit-box-sizing:border-box; /** add this **/
     -ms-box-sizing:border-box; /** add this **/
    }
    

    【讨论】:

    • 只是给遇到这个问题的人的提示,似乎在这一点上几乎所有浏览器都支持主 box-sizing:border-box;版本,因此大多数用户可能不需要 -mox-、-webkit- 和 -ms- 前缀。无论如何,我想它们仍然有助于最大限度地提高兼容性。
    【解决方案2】:

    CSS calc 运算符可能会很有帮助。有了它,您可以在指定左/右填充或左/右页边距时调整可以“丢弃”的宽度。由于您指定了 20px 的总左/右填充,因此您需要从总数中减去 20px。

    #header{
    width: calc(100% - 20px);
    height:100px;
    position:fixed;
    display:inline-block;
    background-color:red;
    padding:0 10px 10px 10px;
    }
    

    【讨论】:

      【解决方案3】:

      尝试使用margin .. 或减少相对于填充区域的宽度。

      #header{
          width:98%;
          height:100px;
          position:fixed;
          display:inline-block;
          background-color:red;
          margin:0 1% 10px 1%;
      }
      

      填充

      填充清除元素内容周围(边框内)的区域。内边距受元素背景颜色的影响。

      保证金

      边距清除元素周围的区域(边界外)。边距没有背景色,完全透明。

      【讨论】:

      • 感谢您的回复,那么headerheader-container的宽度必须是多少?
      【解决方案4】:

      好吧,您似乎想要带填充的全宽。为此,您可以尝试以下代码:

      #header{
      width: initial;
      height:100px;
      position:fixed;
      display:inline-block;
      background-color:red;
      padding:0 10px 10px 10px;
      }
      

      我只是希望这会产生欲望输出。

      【讨论】:

        【解决方案5】:

        这应该可以解决您的问题overflow-x: hidden;

        【讨论】:

          猜你喜欢
          • 2014-10-14
          • 1970-01-01
          • 2010-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多