如何使CSS使用div div一行高度? [英] How to make empty div one line height using CSS?

查看:190
本文介绍了如何使CSS使用div div一行高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以创建一个规则来创建此html

Is it possible to create a rule that will make this html

<div style="width: 100%"></div>

一行高度使用CSS,或者我需要把

one line height using just CSS, or do I need to put &nbsp; as the content?

推荐答案

一些可能性:

line-height 的初始值为 normal ,其使用值与实现相关,但 spec 表示 1.0 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

在我的情况下(FF27 for winXP with font-family:times new roman)该值为 code>,因此您可以使用 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 pseudo-class:

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>

在元素中插入一些内容。

Inserting some content to the element.

例如,您可以添加一个正常空间,并设置> 预包装 code>(或 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, &nbsp; 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.

这篇关于如何使CSS使用div div一行高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆