问题描述
如果在stackoverflow上已经说明了这个问题,请纠正我!如果有的话,我深表歉意,但是我已经寻找了一段时间,只发现了方法而不是为什么.
Please correct me if this question has already been stated on stackoverflow! I apologize dearly if it has but I've been looking for a while and have only found hows not whys.
我的问题是:除非 {display:inline-block;}
已为此指定.指定后,它将根据其子元素的宽度调整其宽度.这确实派上用场,但我认为知道为什么发生这种情况对我来说很重要.这是一些用于视觉表示的代码.预先感谢!
My question is this: Parent divs seem to automatically take up the full width of the page unless { display: inline-block; }
is specified for it. When it is specified, it then adjusts it's width according to the width of it's child element. This really comes in handy, but I feel that it's important for me to know why this is happening. Here is some code for visual representation. Thanks in advance!
我看到有些人将我的问题标记为重复,但是请告诉我在其他问题的何处,它解释为什么显示内联块会自动调整为孩子的身高和宽度.谢谢!
I see that some people have marked my question as a duplicate, but please show me where in the other question it explains why display inline-block automatically adjusts to it's children's height and width. Thank you!
#wrapper {
border: 1px solid black;
display: inline-block;
}
#child_div {
height: 100px;
width: 100px;
border: 1px solid black;
margin: 10px;
}
<div id="wrapper">
<div id="child_div"></div>
</div>
推荐答案
display:inline-block
本质上是 display:inline;
(这是 span
, strong
, em
等的默认设置)和 display:block;
( div
, p
等).
display: inline-block
is basically a sweet-spot between display: inline;
(which is default for span
, strong
, em
, etc.) and display: block;
(which is default for div
, p
, etc).
内联元素是为文本构建的,因此它们应与文本内联流动,并且宽度应与所包含的文本一样宽.因此,您不能设置 inline
元素的宽度.
Inline elements are built for text and thus they should flow inline with the text, and only be as wide as the text they contain. Thus, you can't set the width of an inline
element.
默认情况下,将阻塞元素填充为所有可用宽度,因此它们位于自己的行上,而不是内联.这对诸如段落之类的东西很有用,但是有时您想要较短的行,以便可以调整 block
元素的宽度.
Block elements are made to fill all the available width by default and are thus on their own line rather than flowing inline. This is good for things like paragraphs, but sometimes you want shorter lines so it is possible to adjust the width for block
elements.
行内块元素位于中间.它们像 display:inline;
元素一样内联,但是您可以像 display:block;
元素一样设置宽度.
Inline-block elements are in the middle. They flow inline like display: inline;
elements, but you can set the width like display: block;
elements.
这篇关于为什么inline-block会根据孩子的宽度自动调整其宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!