Justify the last line of a div?

2019-01-01 13:30发布

I don't think the "why?" of this question is important...but what I need to do is to text-align:justify the last line of text from a DIV. Normally, the last line (or the first if there are no other lines, which is the current case) of a div isn't justified, but aligned left. I know it might not make sense at all, but I absolutely need the last line to be justified!

9条回答
一个人的天荒地老
2楼-- · 2019-01-01 13:58

I had an issue where some of the above answers worked, but added a visible new line at the bottom - which was unacceptable, because the box had a background color. I fixed the justification with the code below:

jQuery:

$(".justify").each(function(index, element) {
    var original_height = $(this).height();
    $(this).append("<span style='display: inline-block;visibility: hidden;width:100%;'></span>");
    $(this).height(original_height);
});

HTML:

<div class="justify" style="width:100px; background-color:#CCC">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
查看更多
何处买醉
3楼-- · 2019-01-01 14:03

Let's say I'm working with divs that "for some reason" (there is one pretty good reason) can only have one line....and I want to justify them.

Why don't you use text-align: justify;? It does justify every line. Even if there is just one line.

Edit: I think you are looking for this, as scragz said. Anyway, this works only in IE 5.5 and IE 6.

查看更多
妖精总统
4楼-- · 2019-01-01 14:07

When the !DOCTYPE is HTML5, Kristin's and Jacqui's solutions cause an extra newline, which is hard to remove. If it bothers you (like me), here's yet another idea:

<div style="display: flex;">
  Lorem <span style="flex:1;"></span>
  ipsum <span style="flex:1;"></span>
  dolor <span style="flex:1;"></span>
  sit...
</div>

It has another drawbacks: works for single-line text only, and requires modification of the content as shown above, which isn't always feasible/practical. But there are some situations when this is not problem (like in my case). It can even be useful to have control over the positions where the extra space will be inserted. Styles are inline for brevity only, of course. I tested it with recent FFox/IE only.

查看更多
登录 后发表回答