我创建了div,将其paddings设置为0并在其中添加了一些文本。我注意到div和文本的左边界之间几乎没有空格,而顶部边框和文本之间有2-3个像素空间(与字体大小一起增加)。因此,当您键入文本时,它默认会在其上方获得一些空间,这就像一个边距。我怀疑吗?这是代码
<style type="text/css">
div {
font-size: 50px;
background-color: orange;
padding: 0;
border: black 1px solid;
}
</style>
<div> This is some random text. jjj </div>
答案 0 :(得分:2)
不,纯文本没有默认边距。此外,如果有边际,它将出现在边境之外;内容和边框之间的间距是 padding 。但是也没有默认填充。 (某些HTML元素,如td
具有默认填充,但大多数没有,填充是元素的属性,而不是文本内容。)
如果绘制了边框,则可能在文本字符的上方和下方,在它与元素边框之间看到的空白区域是由两个因素引起的(除了填充,如果设置了填充)。
首先,它是字形设计的一部分,即字符的视觉呈现。字形是使用概念框架设计的,字体高度作为一个部分。字形的高度通常远小于该高度;通常在大写字母之上还有空格。除了j和g之类的字母外,大多数字形都不会延伸到文本的基线之下。所有这些都取决于字体。除了选择字体外,它不会受到影响。
其次,行高,即文本基线之间的距离,通常略大于字体高度。这会导致线下方和上方的间距。通过将line-height
设置为1(在传统版式中称为“设置实体”),或者在某些限制内,通过将line-height
设置为小于1的值,可以删除此间距。通常这不是一个好主意,除了孤立的单行。
以下说明了字体和line-height
的选择如何影响间距。
<style type="text/css">
div {
font-size: 50px;
background-color: orange;
padding: 0;
border: black 1px solid;
margin-bottom: 10px; /* to keep the divs separated */
}
</style>
<div style="font-family: Times New Roman"> This is some random text. jjj </div>
<div style="font-family: Arial"> This is some random text. jjj </div>
<div style="font-family: Arial; line-height: 1"> This is some random text. jjj </div>
<div style="font-family: Arial; line-height: 0.8"> This is some random text. jjj </div>
<div style="font-family: Verdana, Arial; line-height: 1">Glyphs like Å and Ê may extend
beyond the top or bottom of the font. So may glyphs like þ and ẹ.</div>
答案 1 :(得分:0)
不是HTML文本有自己的&#34; margin&#34;,而是元素的默认line-height
属性大于字体占用的数量。
The MDN article on line-height
解释了line-height的默认值是normal
,它的计算结果取决于用户代理(浏览器)。他们说,在大多数浏览器中,行高是字体重量的1.2倍(即〜1.2em
)。
设置line-height
的推荐方法是使用<number>
格式,根据MDN,它使用无单位数作为当前字体大小的乘数。例如:尝试添加到div
CSS规则:
line-height: 1; /* set line-height to be 1.0 * your font size */
当然,您也可以将line-height
设置为特定的像素长度。