使用字母间距填充div [英] Filling div using letter-spacing

查看:62
本文介绍了使用字母间距填充div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是使用 letter-spacing 用文本填充 div .主要问题是,我不知道 div 的宽度.

The problem I'm having is filling a div with text using letter-spacing. The main issue is, I don't know the width of the div.

首先,我正在考虑使用 text-align = justify ,但是自那以后,我一直在黑暗中奔跑,不知道如何解决此问题.我猜想有些脚本魔术可以解决问题.

First I was thinking using, text-align= justify, but since that I've been running in the dark and got no clue to how to solve this. I'm guessing some scripting magic might do the trick.

一个imgur链接,可让您了解我的意思:

An imgur link giving you an idea what I mean:

<div id="container">
 <h1>Sample</h1>
 <p>Another even longer sample text</p>
</div>

这里是显示示例的链接; JSfiddle .

Here is a link showcasing an example; JSfiddle.

推荐答案

根据发布者的评论,似乎JavaScript没问题.这是解决jQuery问题的一种可行方法:

Based the comment of the poster it seems JavaScript is no problem. Here's a possible approach to solve the problem with jQuery:

JSFiddle 1

function dynamicSpacing(full_query, parent_element) {
    $(full_query).css('letter-spacing', 0);
    var content = $(full_query).html();
    var original = content;
    content = content.replace(/(\w|\s)/g, '<span>$1</span>');
    $(full_query).html(content);

    var letter_width = 0;
    var letters_count = 0;
    $(full_query + ' span').each(function() {
        letter_width += $(this).width();
        letters_count++;
    });

    var h1_width = $(parent_element).width();

    var spacing = (h1_width - letter_width) / (letters_count - 1);

    $(full_query).html(original);
    $(full_query).css('letter-spacing', spacing);
}

$(document).ready(function() {
    // Initial
    dynamicSpacing('#container h1', '#container');

    // Refresh
    $(window).resize(function() {
        dynamicSpacing('#container h1', '#container');
    });
});

更新

对于包装程序变得太小的情况进行小的调整: JSFiddle 2

Small tweak for when the wrapper gets too small: JSFiddle 2

这篇关于使用字母间距填充div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆