使用 CSS 对齐最后一行文本

Jak*_*les 2 css

我有一个 CSS 帮助器类,旨在强制“文本”的最后一行(或在预期用途中,内联块 div)与其余部分一样对齐。

这是我得到的代码:

.justify-all-lines
{
    text-align: justify;
    /* IE-only properties that make the :after below unnecessary (we need this because IE 6/7 don't support :after, though) but if they both apply it'll be fine */
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;
}

.justify-all-lines > *:last-child:after
{
    display: inline-block;
    width: 100%;
    content: 'hello';
}

.blocky
{
    display: inline-block;
    /* Make inline block work in IE 6/7 */
    zoom: 1;
    *display: inline;
}
Run Code Online (Sandbox Code Playgroud)

其用途如下:

<div class="justify-all-lines">
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
    <div class="blocky">There is stuff in here.</div>
</div>
Run Code Online (Sandbox Code Playgroud)

但是,我看到“hello”出现在最后一个“块状”div 内,而不是在最后一个“块状”div 之后。我究竟做错了什么?

Jak*_*les 5

工作解决方案:

.justify-all-lines
{
    /* This element will need layout for the text-justify
     * to take effect in IE7 (and possibly previous versions);
     * this will force it, for more info Google "hasLayout in IE"
     */
    overflow: hidden;
    text-align: justify;

    /* For IE6 to IE7 since they don't support :after */
    -ms-text-justify: distribute-all-lines; /* IE8+ */
    text-justify: distribute-all-lines; /* IE5+ */
}

.justify-all-lines:after
{
    /*
     * We don't need IE6 and IE7 inline-block hack support here
     * since they don't support :after anyways (the text-justify
     * properties for them are above)... IE8 and above have native
     * inline-block support so for IE8+, both the text-justify and
     * :after will take effect but it doesn't have any negative
     * effects since this element is invisible
     */
    display: inline-block;
    width: 100%;
    content: '.';
    font-size: 0;
    height: 0;
    line-height: 0;
    visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)

  • 有布局!有布局!!显然,“.justify-all-lines”需要布局才能使“text-justify”起作用。我网站的 CSS 中有“overflow:hidden”,它触发了 hasLayout,但 jsFiddle 中没有。这就解释了。非常感谢您指出这一点,因为我不会注意到!工作 jsFiddle 链接:http://jsfiddle.net/Rk79Y/9/ (2认同)