将空div设为一行的高度 [英] Make empty div of one line height
问题描述
是否可以创建将生成以下HTML的规则:
Is it possible to create a rule that will make the following HTML:
<div style="width: 100%"></div>
仅使用CSS的一行高度,还是我需要放置& ; nbsp;
作为内容?
of one line height using just CSS, or do I need to put
as the content?
推荐答案
某些可能性:
-
设置
高度
(或min-height
)添加到line-height
的使用价值。
line-height
的初始值为 normal
,其使用值取决于实现,但是规范提出一个介于 1.0 $ c之间的数字$ c>和
1.2
The initial value of line-height
is normal
, whose used value is implementation-dependent, but the spec suggests a number between 1.0
and 1.2
就我而言(对于带有 font-family的WinXP,FF27: Times new Roman
),该值是 1.25
,因此您可以使用 height:1.25em
。但是,该值可能与其他字体或实现不同。
In my case (FF27 for winXP with font-family: "times new roman"
) that value is 1.25
, so you could use height: 1.25em
. However, that value might be different with other fonts or implementations.
然后,最好手动设置 line-height
的值,例如 line-height:1.25em
。
Then, it's better to manually set line-height
to some value, like line-height: 1.25em
.
div {
border: 1px solid red;
min-height: 1.25em;
line-height: 1.25;
}
<div></div>
请注意,如果要仅在没有内容时将这些样式设置为元素,可以使用 :empty
伪类:
Note that if you want to set those styles to the elements only when it has no content, you can use the :empty
pseudo-class:
div:empty {
border: 1px solid red;
height: 1.25em;
line-height: 1.25;
}
<div></div>
向元素插入一些内容。
例如,您可以添加普通空间并设置 空白
到前包装
(或 pre
)以防止空间崩溃:
For example, you can add a normal space and set white-space
to pre-wrap
(or pre
) to prevent the space from collapsing:
div {
border: 1px solid red;
white-space: pre-wrap;
}
<div> </div>
零宽度空间(&#8203;
)
div { border: 1px solid red; }
<div></div><!-- There is a zero-width space inside -->
如您所说,& nbsp;
也可以。但是,它是一个不间断的空间,因此其目的是防止自动换行。然后,使用它在语义上是不正确的IMO。
As you say,
would also work. However, it is a non-breaking space, so its purpose is preventing automatic line breaks. Then, using it would be semantically incorrect IMO.
并使用@BoltClock ,这些空格可以插入CSS伪元素,但请注意,这些空格可能不适用于非常老的浏览器。
And as @BoltClock says, those whitespaces could be inserted with CSS pseudo-elements, but note that might not work on very old browsers.
这篇关于将空div设为一行的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!