【问题标题】:Resizing background-color of font in CSS在 CSS 中调整字体的背景颜色
【发布时间】:2014-05-28 18:39:10
【问题描述】:

我有 CSS,它使用Brandon Text 作为字体将文本颜色的范围设置为白色,将背景设置为红色。这是我的 HTML 代码

<div class="headline">
    <span>Long Headline Wrapping Around</span>
</div>

这是我的 CSS 文件

.headline {
    color: white;
}

.headline span {
    font-family: 'Brandon Text', Helvetica, Arial;
    font-size: 36px;
    font-weight: 700px;
    line-height: 56px;
    background-color: #DD3300;
}

但是背景太厚了。有没有办法调整它的大小? line-height 主要用于文本之间的间距,但与背景本身的大小无关。我猜这更多地与 Brandon Text 字体占用多少空间(我不知道这个术语)有关,而不是与 CSS 调整背景大小的能力有关。

编辑:金刚的回答很棒,但现在我有一个额外的并发症。我也在使用 box-shadow,所以上面 .headline span 的 CSS 更像是:

.headline span {
    font-family: 'Brandon Text', Helvetica, Arial;
    font-size: 36px;
    font-weight: 700px;
    line-height: 56px;
    background-color: #DD3300;
    padding: 0;
    display: inline;
    box-shadow: 12px 0 0 #DD3300, -12px 0 0 #DD3300;
}

【问题讨论】:

  • 检查边距和内边距?
  • Background-size 太厚,什么意思?

标签: html css fonts


【解决方案1】:

第一种方法是尝试使用带有阴影颜色whitebox-shadow(理论上与父背景颜色相同):

.headline span {
  ...
  box-shadow:0 3px 0 0 white inset,
  0 -3px 0 0 white inset;
}

Demo 1

第二种方法(我认为更好)是为您的元素使用linear-gradient 背景:

.headline span {
  ...
  background: linear-gradient(transparent 10%, #DD3300 10%, #DD3300 90%, transparent 90%);
}

Demo 2

使用线性渐变背景设置背景大小和背景位置:

.headline span {
   ...
   background: linear-gradient(#DD3300, #DD3300) no-repeat;
   background-position:center;
   background-size:100% 90%;
 }

请注意,您可以使用calc(100% - 3px) 作为background-size 的高度部分。虽然 IEOpeara 的某些旧版本不支持 calc,但请参阅 calc() supports

Demo 3

如您所见,演示 2 和演示 3 使用相对偏移来缩小背景高度。只有第一个demo使用px,这里是另一个demo使用px,但需要浏览器支持多背景功能(目前所有浏览器都支持此功能,只有部分旧版本的IE em>不要,需要IE9+,见CSS3 Multi-background support):

.headline span {
  ...
  background: linear-gradient(#DD3300, #DD3300) no-repeat,
              linear-gradient(#DD3300, #DD3300) no-repeat;
  background-position:left top 3px, left bottom 3px;
  background-size:100% 50%;
}

Demo 4.

【讨论】:

  • 您的回答很有帮助。我已经能够使用带有线性渐变的 Demo 2 来减少背景文本的顶部和底部。不幸的是,因为我也使用 box-shadow 来为类似于这里的 css-tricks.com/multi-line-padded-text 的文本行添加“填充”,结果是一种杠铃外观,盒子阴影是铃铛。我也可以降低盒子阴影高度吗?
【解决方案2】:

也许你正在寻找padding:10px;

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 2014-12-18
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多