CSS:字体上边距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6285885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:43:35  来源:igfitidea点击:

CSS: Font top margin

cssfontsmargin

提问by Tomas Lieberkind

I know the title of this question is stupid, but I couldn't come up with anything better. I have searched for hours on this topic, but either I search for something wrong, or else I have missed out on some CSS basics.

我知道这个问题的标题很愚蠢,但我想不出更好的办法。我已经在这个主题上搜索了几个小时,但要么我搜索了错误的内容,要么我错过了一些 CSS 基础知识。

I have a container div with a 40x40px background-image placed in the top left corner. I want to align the top of the text from an h2 tag with the top of that background-image, which I have tried to do like this.

我有一个容器 div,左上角放置了一个 40x40px 的背景图像。我想将 h2 标签中的文本顶部与该背景图像的顶部对齐,我试图这样做。

HTML:

HTML:

<div id="container">
  <h2 id="title">Lorem</h2>
</div>

CSS:

CSS:

body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
}

#container {
    background: url('test-icon.png') top left no-repeat;
    margin: 200px auto; /* To center the container on the page*/
    min-height: 50px;
    padding-left: 50px; /* To prevent the text from "colliding with the background-image"*/
    width: 300px;
}

#title {
    font-family: "Arial Black", Arial, Helvetica, sans-serif;
    font-size: 1.3em;
    text-transform: uppercase;
}

I have used Eric Meyers CSS reset to get rid of browser specific styles, but have left this out in the above code.

我已经使用 Eric Meyers CSS reset 来摆脱浏览器特定的样式,但在上面的代码中忽略了这一点。

I have created a live example

我创建了一个活生生的例子

The problem is that the background-image and the top of the text from the h2-tag do not align - there is a small "margin" in the top of the h2 tag. This margin seems to change with the font size. When I use Google Chromes inspector, it tells me that the margin and padding of the h2 and div tag are all 0px. As browsers render fonts differently, I don't mant to mess around with negative margins in case it breaks the layout. Is there a way to "safely" get rid of this margin? To be totally clear, what I want to acheive is this.

问题是背景图像和 h2 标签中的文本顶部不对齐 - h2 标签顶部有一个小的“边距”。这个边距似乎随着字体大小而变化。当我使用谷歌浏览器检查器时,它告诉我 h2 和 div 标签的边距和填充都是 0px。由于浏览器以不同的方式呈现字体,因此我不想乱用负边距,以防它破坏布局。有没有办法“安全地”摆脱这个保证金?完全清楚,我想要实现的是这个

采纳答案by mu is too short

I think your problem is the line-heighton the <h2>. A bit of fiddling around tells me that you want it to be:

我认为你的问题是line-height<h2>. 稍微摆弄一下告诉我你希望它是:

line-height: 10px;

You might need to use pxfor your font-sizeto get things to work consistently in various browsers.

您可能需要使用pxfont-size在各种浏览器一致地把事情的工作。

回答by simonfoust

Have you tried line-height: 1; ?

您是否尝试过 line-height: 1; ?