如何在CSS中实现负填充?

时间:2016-09-16 23:28:21

标签: html css fonts css-position padding

我正在寻找一种在CSS中有效实现负填充的方法。

问题

我的网页上有一个h1元素,目前有以下代码与之关联:



h1 {
  background-color: #375E97;
  color: #FFFFFF;
  font-size: 50px;
  font-family: 'Righteous', cursive;
  text-transform: uppercase;
  text-align: center;
  padding: 0;
  margin: 0 auto;
  height: 49px;
}

<head>
  <link href="https://fonts.googleapis.com/css?family=Righteous|Roboto:400,700,400i" rel="stylesheet">
</head>

<body>
  <h1>Lorem Ipsun Al</h1>
</body>
&#13;
&#13;
&#13;

您可以看到,因为我添加了height: 49px;,文本看起来好像正在流入页面的其余部分。我希望实现这种外观,但也是文本的顶部,而不仅仅是底部。

我尝试过什么

我试过了:

  • padding元素设置margin0h1
  • 使用vertical-align的各种值。
  • height设置为许多不同的值。
  • 设置所有h1的父元素&#39; paddingmargin0

我认为我遇到的问题是我使用的字体顶部(和大多数字体)有一些空间。这就是为什么我希望能够实现负填充,在不移动内容框的情况下在屏幕上移动文本。

3 个答案:

答案 0 :(得分:5)

它完全取决于您使用的字体,但在您的特定情况下height: 34pxline-height: 34px;执行您想要的操作:

h1 {
  background-color: #375E97;
  color: #FFFFFF;
  
  font-size: 50px;
  font-family: 'Righteous', cursive;
  text-transform: uppercase;
  text-align: center;
  
  padding: 0px;
  margin: 0 auto;
  
  height: 34px;
  line-height: 34px;
}
<!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Righteous|Roboto:400,700,400i" rel="stylesheet">
</head>

<body>
  <h1>Lorem Ipsun Al</h1>
</body>

</html>

答案 1 :(得分:1)

您没有尝试的一件事是调整line-height

  

10.8 Line height calculations: the line-height and vertical-align properties

     

在块容器元素上,其内容由内联级别组成   元素line-height指定线框的最小高度   在元素内。

h1 {
    background-color: #375E97;
    color: #FFFFFF;
    font-size: 50px;
    font-family: 'Righteous', cursive;
    text-transform: uppercase;
    text-align: center;
    padding: 0;
    margin: 0 auto;
    line-height: .6;
}
<h1>Lorem Ipsun Al</h1>

答案 2 :(得分:0)

在内部内容上使用负边距可以实现与负填充相同的功能。