Html Div 宽度 = 100%?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5251048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Div width = 100%?
提问by anonymous
I have JS generated content and want a div EXACTLY around it.
我有 JS 生成的内容,并希望在它周围有一个 div。
I don't know why, but the div parent is always 100% wide.
我不知道为什么,但 div 父级总是 100% 宽。
I thought I have div width: 100% somewhere, but surprisingly it looks almost the same in jsfiddle:
我以为我有 div width: 100% 某处,但令人惊讶的是它在 jsfiddle 中看起来几乎相同:
So why the outer div is always 100% wide? And how to fix that? I was trying with display: inline, but it sets width to 0px ;/
那么为什么外部 div 总是 100% 宽?以及如何解决这个问题?我正在尝试使用 display: inline,但它将宽度设置为 0px ;/
CSS:
CSS:
.outer {
border: solid 1px red;
}
.item {
height: 300px;
width: 400px;
border: solid 1px blue;
}
.allright {
height: 300px;
width: 400px;
border: solid 1px blue;
outline: solid 1px red;
}
HTML:
HTML:
<p>I don't know where "outer" div 100% width comes from?</p>
<div class="outer">
<div class="item">
<p>Something big!</p>
</div>
</div>
I always thought it'd look like that:
<div class="allright"></div>
I can't set outer div width (width: xxxpx) because all the content is dynamically created.
我无法设置外部 div 宽度(宽度:xxxpx),因为所有内容都是动态创建的。
回答by zzzzBov
It sounds like you need to read the Visual Formatting Model.
听起来您需要阅读Visual Formatting Model。
display: block;
causes block-level items to automatically fill their parent container.
display: block;
导致块级项目自动填充其父容器。
CSS is designed in a way that lends itself to the child elements filling their parents, rather than the parents conforming to the children.
CSS 的设计方式是让子元素填充其父元素,而不是父元素符合子元素。
回答by Ivan Ivani?
div is block element. Block elements are 100% width of parent element, if width is not specified.
div 是块元素。如果未指定宽度,则块元素是父元素的 100% 宽度。
回答by jonezy
it's taking up all the available space based on it's parent container, exactly what it's supposed to do. If you want it to be a specific width set the width:; of the element.
它根据它的父容器占用了所有可用空间,这正是它应该做的。如果您希望它是特定宽度,请设置宽度:; 元素的。
回答by ngstschr
If you find the w3.org documentation a little bit dry or too technical, here is a more accessible explanation of the CSS box model: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model
如果您发现 w3.org 文档有点枯燥或过于技术性,这里有一个更容易理解的 CSS 盒模型解释:https: //developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/ Introduction_to_the_CSS_box_model