2

Given the following:

<div style="float: left; line-height: 24px;">
    Would<br />
    Be Nice<br />
    If Aligned<br />
To the "top"<br />
</div>

Observe that text is aligned to the bottom of the "line" in Chrome (IE seems to center text).

Is there a way, without wrapping each line in a div (or span) to vertically align the text within its "line"?

JSfiddle

Dunno
  • 3,632
  • 3
  • 28
  • 43
dwellman
  • 175
  • 2
  • 8
  • 5
    Can you be a bit more specific of wat you're trying to achieve? jsfiddle.net might help you with this! – Dieterg Nov 26 '13 at 19:06
  • I think he means that the `line-height` adds more space above the lines of text, not below them (you can see that when you select the contents). Added a jsfiddle. – Dunno Nov 26 '13 at 19:10
  • 1
    Line-height is always added above and below each character. So if your font-size is 12px and you have a line-height of 18px, you'll get 3px above and 3px below each "line". Each of those 3px spaces is called a "half-leading" – KyleMit Nov 26 '13 at 19:27

1 Answers1

2

Some issues with this approach:

From align block elements on top when using line-height:

Line-height is always added above and below each character. So if your font-size is 12px and you have a line-height of 18px, you'll get 3px above and 3px below each "line". Each of those 3px spaces is called a "half-leading"

The solution there was to position each element relatively, and then apply a negative margin, but we can't do that here because each line is not it's own element, as per:

Is there a way, without wrapping each line in a div (or span)

If you were really resistant to modifying the markup, here's a JavaScript / CSS work around. We can't top align when we have a "half-leading" above the text. Instead, we need to get rid of the the line-height spacing on the top and bottom, and create our own spacing just on the bottom. How do we know where the bottom of each line is? Well, we can use the <br/> element, but we can't style a carriage return.

So we'll use javascript to get something we can style and then add some spacing that way:

JavaScript:

$('br').before('<div class="spacer"></div>');

CSS:

.spacer {
    height: 24px;
    display: inline-block;
}

Working Demo in JsFiddle

Which should look like this:

screenshot

**Note: with an inline-block div, you'll have to set the height to what you'd like for a line-heightand vertically align the div text to the top. You could also use a regular div with a negative margin-top to eat up the extra space that it takes in between paragraphs.*

Community
  • 1
  • 1
KyleMit
  • 30,350
  • 66
  • 462
  • 664