Home  >  Q&A  >  body text

css - 背景颜色填充屏幕宽度问题

一个h1标题,设置了width:100%,缩放出现滚动条时,出现空白区域

代码如下:
css:

h1{
width:100%;
height:50px;
line-height:50px;
background-color:blue;
}

p{
  width:1000px;
  height:200px;
  border:1px solid red
}

html:

<h1>欢迎来到………………</h1>

<p></p>

如上的代码,在放大网页的时候,会出现h1标签背景颜色没有占满屏幕宽度。

怎么解决??

天蓬老师天蓬老师2716 days ago653

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 12:09:25

    The width:100%; of h1 is calculated relative to the width of its parent element body, and the width of body defaults to the width of the current window (when the margin and padding of html and body are 0). Therefore, when the window is reduced, the width of the body decreases, and the width of h1 decreases accordingly. The scroll bar is generated due to the large width of p. At this time, p has exceeded the width range of the body. You can add a body{border: 1px solid blue;} to see the actual situation.

    reply
    0
  • PHPz

    PHPz2017-04-17 12:09:25

    *{
        padding:0;
        margin:0;
    }

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:09:25

    I am confused by your question, if you set margin: 0. Did you do the test on your mobile phone? To enlarge the page, does it mean to reduce the window?
    First of all, this 100% is calculated based on its parent element, which is the body. The time is when your window is first loaded or the window size is changed, so if you shrink the window (that is, you say enlarge the page ) makes the width less than 1000px, then the width of the body will be less than 1000px as its parent element, then the width of h1 will naturally be less than 1000px, a scroll bar will appear, and the width of the entire page will be supported by the maximum width (you are here p), of course there will be a blank space when you pull the scroll bar at this time~~~~
    The solution @jasonintju has already told you, you still need to look at the suggestions of the 1.7k seniors carefully. As a beginner, I put them Seen as the greatest resource.
    If you don’t want to set the min-width of h1 directly, then set the min-width of the body and make it large enough (the width of the widest element) so that the child elements of the body will not have this problem. .

    reply
    0
  • Cancelreply