将 div 设置为其包含文本的宽度?
Set div to the width of its containing text?
我有一个 div class heading
,其中包含动态生成的文本,我想使用 border-bottom
为其添加下划线。但是如果我设置 .heading {width:auto}
然后 div 水平填充它的容器,并且下划线太长了。
如何使 div 与包含的文本一样长?
Visual formatting model - 'Inline-block', non-replaced elements in normal flow:
If width
is auto
, the used value is the shrink-to-fit width as for floating elements.
A computed value of auto
for margin-left
or margin-right
becomes a used value of 0
.
因此您可以将元素的 display
更改为 inline-block
。
这样做时,元素的宽度将 "shrink to fit" 其内容,在本例中为文本。
.heading {
background: blue;
display: inline-block;
}
<div class="heading">text</div>
还值得指出的是,您可以省略 width: auto
,因为 auto
已经是默认值。
显然,您还可以将元素的类型从 div
更改为 span
,默认情况下为 inline
。
我有一个 div class heading
,其中包含动态生成的文本,我想使用 border-bottom
为其添加下划线。但是如果我设置 .heading {width:auto}
然后 div 水平填充它的容器,并且下划线太长了。
如何使 div 与包含的文本一样长?
Visual formatting model - 'Inline-block', non-replaced elements in normal flow:
If
width
isauto
, the used value is the shrink-to-fit width as for floating elements.A computed value of
auto
formargin-left
ormargin-right
becomes a used value of0
.
因此您可以将元素的 display
更改为 inline-block
。
这样做时,元素的宽度将 "shrink to fit" 其内容,在本例中为文本。
.heading {
background: blue;
display: inline-block;
}
<div class="heading">text</div>
还值得指出的是,您可以省略 width: auto
,因为 auto
已经是默认值。
显然,您还可以将元素的类型从 div
更改为 span
,默认情况下为 inline
。