Div width = 100%?

那年仲夏 提交于 2019-12-18 06:35:45

问题


I have JS generated content and want a div EXACTLY around it.

I don't know why, but the div parent is always 100% wide.

I thought I have div width: 100% somewhere, but surprisingly it looks almost the same in jsfiddle:

http://jsfiddle.net/f2BXx/2/

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 ;/

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:

<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.


回答1:


It sounds like you need to read the Visual Formatting Model.

display: block; causes block-level items to automatically fill their parent container.

CSS is designed in a way that lends itself to the child elements filling their parents, rather than the parents conforming to the children.




回答2:


div is block element. Block elements are 100% width of parent element, if width is not specified.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5251048/div-width-100

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!