【问题标题】:css to format line 1 and 2 of my h1 differently? & change position of line breakcss 以不同方式格式化我的 h1 的第 1 行和第 2 行? & 改变换行位置
【发布时间】:2012-02-01 01:45:22
【问题描述】:

您好,我在 wordpress 中使用了一个特色帖子小部件,它显示我的 h1 标题超过 2 行。但是我想更改边距或换行符,而不是说 第一行是“工伤”,第二行是“预防”, 第一行是“工作场所”,第二行是“伤害预防”

任何想法。我试过使用伪第一行命令,但没有运气,即。

#home-header-right .featuredpage .post-7  h2:first-line,
#home-header-right .featuredpage .post-20  h2:first-line, 
#home-header-right .featuredpage .post-7  a:first-line,
#home-header-right .featuredpage .post-20  a:first-line  {
    padding: 0 50px 0 0;
}

【问题讨论】:

  • :first-line 不幸的是对你想做的事情没有用。

标签: css padding line-breaks pseudo-element


【解决方案1】:

:first-line 选择的文本是内联级文本块,不能应用填充和边距。您可以尝试在其上设置 display: block 以查看它是否有效,但就 W3C Wiki 而言,您只能在该文本上使用以下 CSS 属性:

  • font 属性、colorbackground 属性、word-spacingletter-spacingtext-decorationvertical-aligntext-transformline-height

【讨论】:

    【解决方案2】:

    如果你想打破第一个单词的文字,我建议你把它换成另一个元素:

    <h1><span>Workplace</span> Injury Prevention</h1>
    
    h1 span {
        display: block;
    }
    

    示例:http://dabblet.com/gist/1714493

    附加元素是非语义的,但不如硬编码的&lt;br&gt;,并且比尝试弄乱:first-line 伪元素更可靠。

    编辑:如果您不能在帖子标题中使用 HTML 并且不介意使用一点 jQuery,您可以像这样动态包装文本:

    (function($) {
        $('h1:contains(Workplace Injury Prevention)')
            .html(function(i, html) {
                return html.replace('Workplace', '<span>Workplace</span>');
            });
        ;
    })(jQuery);
    

    示例:http://jsfiddle.net/deZKd/

    要对其他帖子标题执行此操作,您需要更通用的内容:

    (function($) {
        $('h1')
            .html(function(i, html) {
                return html.replace(/^(\w+)\b/, '<span>$1</span>');
            });
        ;
    })(jQuery);
    

    示例:http://jsfiddle.net/deZKd/1/

    (请记住,在这两个示例中,您都需要更改选择器以仅匹配小部件中的帖子标题,例如#recent-posts-widget h1:contains(…)。)

    【讨论】:

    • 谢谢。问题是标题是从精选帖子小部件中提取的,因此我没有机会将其包装在跨度标签中。因此没有简单的解决方法?
    • 您可以使用text-indent 将前几个单词推过去,但这会破坏对齐方式。由于效果纯粹是装饰性的,因此您可以合理地考虑使用 JavaScript;我会回来的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2017-06-11
    相关资源
    最近更新 更多