简体   繁体   English

如何使元素采用html元素的宽度?

[英]How can I make elements take width of html element?

For whatever reason, I can't seem to put the right words in my search engine. 无论出于什么原因,我似乎都无法在搜索引擎中输入正确的单词。 It seems like a really easy thing. 看起来真的很容易。 Let's say I have simple markup as follows: 假设我有如下简单的标记:

<div>Hello!</div>

And I apply the following styles: 我应用以下样式:

body {
  background: blue;
}

div {
  background: green;
  width: 100%;
}

Now ideally, I'd like the green to stretch across the entire screen, but for whatever reason theres a buffer between the ends of the window and the div, that are blue. 现在,理想情况下,我希望绿色延伸到整个屏幕上,但是无论出于何种原因,窗口和div的末端之间都是蓝色的缓冲区。 When I go to inspect the div, I note that there is 0 padding/margin and just the content box. 当我去检查div时,我注意到填充/边距为0,只有内容框。 When I inspect the HTML element. 当我检查HTML元素时。 it's just the content with no padding/margin as well. 它只是没有填充/边距的内容。

I guess my question is, how can I get rid of that blue buffer area between the html and the containing div? 我想我的问题是,如何摆脱html和包含div之间的蓝色缓冲区? The only way I have successfully done it, is negative margins on the div, but that seems hacky. 我成功完成此操作的唯一方法是在div上设置负边距,但这似乎很麻烦。 Any thoughts? 有什么想法吗?

Even without any CSS applied, every browser does some default styling of elements. 即使没有应用任何CSS,每个浏览器也会对元素进行一些默认样式设置。 This includes margin on the body element. 这包括body元素上的边距。 To overwrite these default styles (which you can inspect via your browser's developer tools, if any - for example via F12 in Chrome), you just set custom CSS rules accordingly. 要覆盖这些默认样式(您可以通过浏览器的开发者工具进行检查,如果有的话,例如,通过Chrome中的F12进行检查),只需设置相应的自定义CSS规则即可。 For your specific problem, you should add margin: 0 to the styling of the body tag. 对于您的特定问题,应在body标签的样式中添加margin: 0

Now, since every browser has different defaults, many developers decide to reset the styling entirely before applying their own. 现在,由于每个浏览器都有不同的默认值,因此许多开发人员决定在应用自己的样式之前完全重置样式。 This can make for a more consistent and streamlined CSS developing process. 这可以使CSS开发过程更加一致和简化。 There are several of these reset stylings available, a famous one being Eric Meyer's CSS reset . 这些重置样式有几种,其中一个著名的就是Eric Meyer的CSS reset

Body element has default margin at every direction 8px long, so just rewrite this default. 主体元素在每个方向上都有8px长的默认边距,因此只需重写此默认值即可。

body {
   margin: 0;
   background: blue;
}

@Edit: ...also It's great example to practice 'Developer Tools' using. @Edit:...也是实践“开发人员工具”使用的一个很好的例子。 There's nice guide: https://developers.google.com/web/tools/chrome-devtools/inspect-styles/ 有很好的指南: https : //developers.google.com/web/tools/chrome-devtools/inspect-styles/

You should consult the CSS box model when you have questions like this one. 遇到类似这样的问题时,应咨询CSS盒模型 You just need to remove the margin from the body. 您只需要从身体上去除边缘。

 body { background: blue; margin: 0px } div { background: green; width: 100%; } 
 <div>Hello!</div> 

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

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