简体   繁体   中英

CSS: How to make background of an element stretch across the entire page?

I'm starting to learn CSS and really don't know how to deal with this problem. I am trying to make a solid colored top bar similiar to the black bar on bottom of this page. However when I try to do it, the color sort of makes a box around the text, instead of going from the borders of the page. I tried playing around with width/height with no success.

Thanks

EDIT:

 body { margin:0;}
.
.
.
#bar{
      height: 100%; //these dont do anything
      width: 100%;
   background-color:black;}
<div id=bar>       <h1> <a href="index.html"> <span id=stuff>stuff </span></a>
       <br> <span id=stuff> stuff stuff stuff</span> </h1> 

       <ul>
<li><a href="#stuff">stuff stuff stuff</a></li>
<li><a href="#stuff">stuff stuff stuff</a></li>
<li><a href="#stuff">stuff stuff stuff</a></li>
<li><a href="#stuff">stuff stuff stuff</a></li>
<li><a href="#stuff">stuff stuff stuff</a></li>
<li><a href="#stuff">stuff stuff stuff</a></li>
</ul>

</div>

您是否在背景图像上尝试了100%的宽度和高度?

1) You should set width: 100%; on the element and make sure all parent elements have that too. In this way the element is told to stretch out to the full width of the page. [You did this propably already :) ]

2) Also, make sure that the element is a block element or inline-block element (with display: inline-block ), so it doesn't act as a normal inline element (which will be as big as its contents needs).

Most browsers set default margins, you can override them including body { margin:0; } body { margin:0; } in your CSS.

UPDATE: you've got h1 there, it also has its own margins, so add h1 {margin:0;} as well.

 body { margin: 0 } #topBar { background: black; color: white; } 
 <div id=topBar>Top bar</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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