Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

html - Vertically center text that has no descenders?

Suppose I have a single line of text that is in all caps (e.g. with text-transform: uppercase). I want to center this text vertically in a div. I don't need to worry about multi-line text.

There are several ways to center things vertically in CSS (e.g. check this out). Unfortunately, all these methods take descenders into account, and my text doesn't have any descenders so it isn't centered perfectly. Basically, I want to center the portion of the text from the baseline to the cap height.

Is there any way to vertically center a line of capitalized text? Right now I'm using position: relative and manually tweaking it until it is centered (e.g. with top: 2px), but this is clearly not a robust solution (it is very dependent on the way the browser renders text, what fonts are available, etc.). Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

line-height is actually given when we want to align the block elements in between along y-axis.

For example, i have a singled line text in w3schools and para height is 20px. The paragraph will be written in its own default way but if i use line-height equals the height of the paragraph then text in say W3schools will be aligned in the middle along y-axis. While if you want to horizontally align (x-axis align) your text then text-align:center is used for this purpose.

Remember, line-height do not totally depend on the height of its own element height. But it changes as follows.

  1. If you have a single line text, height is 20px then give line-height: 20px to vertically align the text or vertically middle of text.
  2. If you have a two line of text, height is 20px then give the line-height:10px and with the small padding-top to vertically align the text.

I hope this will lift you up. And i think you will not need to browse google more. If more you want explanation then i will give you jfiddle code. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...