简体   繁体   English

样式标头,宽度为100%,不使用position属性

[英]Style header with `width: 100%` without using the `position` property

Here is my HTML structure: 这是我的HTML结构:

 div { position: absolute; width: 100%; top: 0; left: 0; background-color: gray; color: white; text-align: center; } 
 <div>header</div> 

Can I make exactly the same thing (like the result of code above) without position property ? 没有 position属性,我可以做完全一样的事情吗(如上面的代码结果)

Sure, just be sure to set margin: 0; 当然,只要确保将margin: 0;设置为margin: 0; and padding: 0; padding: 0; on your html and body elements as well, because most browser stylesheets set non-zero default values for these properties: htmlbody元素上也是如此,因为大多数浏览器样式表都为这些属性设置了非零的默认值:

 div { width: 100%; background-color: gray; color: white; text-align: center; } html, body { margin: 0; padding: 0; } 
 <div>header</div> 

To debug, you can see... 要调试,您可以看到...

 div { width: 100%; top: 0; left: 0; background-color: gray; color: white; text-align: center; } * { border: 1px solid red; } 
 <div>header</div> 

One soution could will be remove margin/padding from body. 一种感觉可能是去除身体的边缘/填充。

(NOTE: if you are using bootstrap like row etc, you might have margin left or right for 15px, for that situation you might need use xxx { margin: 0 !important; padding: 0 !important;} (注意:如果您使用的是引导程序,例如row等,则可能需要左右留出15px的空白,在这种情况下,您可能需要使用xxx { margin: 0 !important; padding: 0 !important;}

 div{ width: 100%; top: 0; left: 0; background-color: gray; color: white; text-align: center; } body { margin: 0; padding: 0; } 
 <div>header</div> 

Sure you can, for every block element, since their default width is 100%. 因为每个块元素的默认width均为100%,所以可以确定。 You can then also erase the width: 100%, and the top/left properties. 然后,您还可以擦除宽度:100%,以及top / left属性。

To get the same effect as in your example, just make sure to set margin to 0 for html and body , which sets their otherwise default margin to zero: 要获得与示例相同的效果,只需确保将htmlbody margin设置为0,否则将其默认的margin设置为零:

 html, body { margin: 0; } div{ background-color: gray; color: white; text-align: center; } 
 <div>header</div> 

Here by default browser (User agent stylesheet) applied a default margin to the body tag. 默认情况下,浏览器(用户代理样式表)在此处将默认边距应用于body标签。 So u can override the style of the body tag. 因此,您可以覆盖body标签的样式。

 div{ width: 100%; background-color: gray; color: white; text-align: center; } body { margin: 0px; } 
 <div>header</div> 

Hope this is what you where looking for. 希望这是您要寻找的东西。

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

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