【问题标题】:Make text height 100% of div?使文本高度为 div 的 100%?
【发布时间】:2012-05-29 22:28:12
【问题描述】:

我正在尝试将文本设置为 div 的 100% 高度,但它不起作用。
它只是成为body { font-size:?; } 的 100%。

有没有办法让它跟随 div 的高度?
div 高度是整个页面的 4%,当您调整大小/更改分辨率时,我不想让文本跟随它。

【问题讨论】:

  • 你是想通过 CSS 来实现,还是有一个 JS 函数来根据 div 高度设置字体大小?
  • 我可能会使用 javascript,但由于我对此几乎一无所知,所以我需要一些指导。

标签: css text fonts height


【解决方案1】:

为了得到我想要的结果,我不得不使用这个代码:

// Cache the div so that the browser doesn't have to find it every time the window is resized.
var $div = $('li.leaf.item');

// Run the following when the window is resized, and also trigger it once to begin with.
$(window).resize(function () {
   // Get the current height of the div and save it as a variable.
   var height = $div.height();
   // Set the font-size and line-height of the text within the div according to the current height.
   $div.css({
      'font-size': (height/2) + 'px',
      'line-height': height + 'px'
   })
}).trigger('resize');​

感谢 josuanhibbert@css-tricks 的帮助!

【讨论】:

  • 应该有 javascript 库允许自定义 css 单元提供更多选项。喜欢适合的内容,填写父母。 % 父级高度。等
  • +1 表示概念。我试图确定它改变的速度然后以相同的速度改变字体大小,这让我很愚蠢。像这样做简单的数学运算更容易。
【解决方案2】:

2015年,您可以使用viewport units。这将允许您以高度单位设置字体大小,代表视口高度的 1%。

所以在你的情况下font-size: 4vh 会达到预期的效果。

注意:这不会像你问的那样相对于父 div,而是相对于视口高度。

【讨论】:

  • 视口单位仍然有问题。也许一年后(我希望是半年)它的支持就足够了
【解决方案3】:

使用 CSS 你无法做到这一点。而不是使用 javascript。

检查这些:

  1. http://fittextjs.com/
  2. Have font size change according to size of div
  3. resize font to fit in a div

【讨论】:

  • 我无法让这些工作。这是我要调整的菜单文本。它看起来像这样:<ul class="cnt-main-menu">\n <li class="item"><a href="/">Menu1</a></li>\n </ul> cnt-main-menu 的高度是整个页面的 4%。我将如何使用 fittextjs 使文本跟随 cnt-main-menu 框?
  • 阅读:fittext usage
  • 所有这些链接都用于调整相对于宽度而不是高度的大小。
【解决方案4】:

如果您想要仅使用 CSS 的 div 大小为 100% 的文本,则必须更改 font-size 和 line-height 属性。这是我的解决方案:

.divWithText {
    background-color: white;
    border-radius: 10px;
    text-align: center;
    text-decoration: bold;
    color: black;

    height: 15vh;
    font-size: 15vh;
    line-height: 15vh;
}

【讨论】:

    【解决方案5】:

    试试这个

    font
    {
      position:absolute;
      width:100%;
      height:100%;
      font-family:Verdana, Geneva, sans-serif;
      font-size:15px;
      font-weight:normal;
    }
    

    【讨论】:

    • 这会设置一个固定的字体大小。
    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 2011-07-05
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多