Padding causes horizontal scroll - it increases the width

回眸只為那壹抹淺笑 提交于 2019-12-01 08:17:23

问题


Please look at this code:

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

here is the demo . The header must have 100% width and 10px padding from left,right and bottom. please look at this picture

this is the layout of #header by firebug. as you can see the right padding is not in the image because the 10px padding is added to the #header width (you can test it). how can I set 100% width for #header and 10px padding for left,right and bottom without increasing the width?


回答1:


try this

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

or

 #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 **/
}



回答2:


The CSS calc operator may prove helpful. With it, you can adjust the width that can be 'thrown off' when you specify left/right padding or left/right margin. Since you specified total left/right padding of 20px, then 20px would be what you need to subtract from the total with.

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



回答3:


try with margin .. or reduce your width with respect to your padding area.

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

Padding

The padding clears an area around the content (inside the border) of an element. The padding is affected by the background color of the element.

Margin

The margin clears an area around an element (outside the border). The margin does not have a background color, and is completely transparent.




回答4:


Well it seems that you want want full width with padding. for this you can try this code:

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

i just hope this will give desire output.




回答5:


This should solve your problem overflow-x: hidden;



来源:https://stackoverflow.com/questions/21621584/padding-causes-horizontal-scroll-it-increases-the-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!